5๐
โ
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
:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView
class PostListView(LoginRequiredMixin, ListView):
model = Post
template_name = 'dashboard/postlist.html'
paginate_by = 5
queryset = Post.objects.order_by('-date')
In your dashboard/postlist.html
template, then you can add logic to render the buttons. Like for example:
<!-- render the list -->
{% if is_paginated %}
{% if page_obj.has_previous %}
<a href="?page={{ page_obj.previous_page_number }}">previous</a>
{% endif %}
{% if page_obj.has_next %}
<a href="?page={{ page_obj.next_page_number }}">next</a>
{% endif %}
{% endif %}
In the urls.py
you can then use the PostListView.as_view()
instead of the PostLists
. So the ListView
will here handle authentication check, slicing, pagination, etc.
Source:stackexchange.com