如何通过此使用分页不起作用

views.py paginate_by is not working, is there any alternative for this.

class PostListView(ListView):
    template_name = 'all_users/doctor/main.html'
    model = Post
    context_object_name = 'posts'
    paginate_by = 3

    def get(self, request, **kwargs):
        query = self.request.user
        post = Post.objects.filter(author=User.objects.get(username=query)).order_by('-date_posted')
        context = {
            'posts': post,
        }
        return render(request, self.template_name, context)
评论
pquo
pquo

Django will paginate the queryset that originates from the get_queryset. So you can implement the view with:

from django.contrib.auth.mixins import LoginRequiredMixin

class PostListView(LoginRequiredMixin, ListView):
    template_name = 'all_users/doctor/main.html'
    model = Post
    context_object_name = 'posts'
    paginate_by = 3

    def get_queryset(self, *args, **kwargs):
        super().get_queryset(*args, **kwargs).filter(
            author=self.request.user
        ).order_by('-date_posted')

It will add the Page object to the context with the name page_obj. So you can iterate over it with:

{% for post in page_obj %}
    {{ post }}
{% endfor %}

Note: You can limit views to a class-based view to authenticated users with the LoginRequiredMixin mixin [Django-doc].

点赞
评论