Issue
The default class based view pagination returning all object. I have an my account page for my each individual user where I need to show pagination number. By default pagination is same for all user. Let you explain little bit. If user A have 10 items and I listed 2 items per page then user A will be see total 5 page in his account which is fine but user B haven't any items and he is currently seeing only pagination number like page1,page2,page3... in his account because the current pagination returning all items from database. here is my code:
views.py
class BlogMyAccount(ListView):
paginate_by = 10
model = Blog
template_name = 'blog/my-account.html'
ordering = ['-id']
#html
{% for blog in object_list %}
{% if user.id == blog.author.id %}
....my code
{% endif %}
{% endfor %}
<!---pagination code---->
<ul class="pagination justify-content-center mb-4">
{% if page_obj.has_previous %}
<li class="page-item"><a class="page-link" href="?page=1">First Page</a></li>
<li class="page-item"><a class="page-link" href="?page={{ page_obj.previous_page_number }}">← Back</a></li>
{% endif %}
{% if page_obj.has_next %}
<li class="page-item"><a class="page-link" href="?page={{ page_obj.next_page_number }}">Next Page →</a></li>
{% endif %}
{% for i in paginator.page_range %}
{% if page_obj.number == i %}
<li class="page-item"><a class="page-link" href="#!">{{ i }}</a></li>
{% elif i > page_obj.number|add:'-3' and i < page_obj.number|add:'3' %}
<li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
{%endif%}
{% endfor %}
<li class="page-item"><a class="page-link" href="?page={{ page_obj.paginator.num_pages }}">Last Page</a></li>
</ul>
in function based view I am passing user object like this in pagination:
notifications = Notifications.objects.all().filter(user=user).order_by('-date')
paginator = Paginator(notifications, 20) # Show 25 contacts per page.
I tried to apply same method by using context in my classed view but didn't work. Pagination is same for all user in class based view.
Solution
You need to filter the queryset the same way you did in FBV. Override get_queryset() to only return objects associated with your requesting user.
class BlogMyAccount(ListView):
paginate_by = 10
model = Blog
template_name = 'blog/my-account.html'
ordering = ['-id']
def get_queryset(self):
queryset = Blog.objects.filter(author=self.request.user)
return queryset
Also you dont need to call .all() on Notifications.objects, it is already a queryset, Notifications.objects.filter() is okay.
If possible, move ordering to the models.py file, as in:
class Meta:
ordering = ['-id']
Answered By - kraupn3r
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.