On my page all the blog posts will be showing up. So I wanted to implement a next/previous button to better my page.
def PostLists(request):
num = request.session.get('num',-5)
request.session['num'] = num
num = num + 5
exp = Post.objects.order_by('-date').all()[num:(num+5)]
context = {
'object_list': exp
}
if (request.user.is_authenticated):
return render(request, 'dashboard/postlist.html', context=context)
else:
return redirect('login')
I added a next button in my html code which will redirect me to my the same views.py function as shown above and the variable(num) shall increment by 5 thus showing me my next 5 posts. However this seems not to be working as I see the same 5 posts always.
Is there a better way to implement a next/previous button? If so could you please specify that? Thanks a lot!
I think you try to do too much yourself. Django has support for this, it even has a lot of support when rendering lists, and enforcing that the user is logged in.
We can use a class-based view for this: a
ListView:In your
dashboard/postlist.htmltemplate, then you can add logic to render the buttons. Like for example:In the
urls.pyyou can then use thePostListView.as_view()instead of thePostLists. So theListViewwill here handle authentication check, slicing, pagination, etc.