模板Django中的分页有问题吗?

时间:2018-09-09 16:35:23

标签: python django

我的应用程序中有这种观点,我尝试在模板中进行分页。但是上一个和下一个不起作用。怎么了?

class ForMenView(ListView):
    model = Post
    template_name = 'man_index.html'
    context_object_name = 'all_posts'
    paginate_by = 1

    def get_queryset(self):
        query = self.request.GET.get('q')
        qs = Post.objects.filter(sex='M', is_published=True)
        if query:
            return qs.filter(title__icontains=query)
        return qs

    def get_paginate_by(self, queryset):
        user = self.request.user
        if user.is_authenticated and user.sex == 'M':
            return 1
        return self.paginate_by


    def dispatch(self, request, *args, **kwargs):
        user = self.request.user
        if user.is_authenticated and user.sex == 'W':
            return redirect('/forwomen')  # please replace it with the view name
        else:
            return super(ForMenView, self).dispatch(self.request ,*args, **kwargs)


    def get_context_data(self, *args, **kwargs):
        kwargs = super(ForMenView, self).get_context_data(*args, **kwargs)
        kwargs['page_range'] = kwargs['paginator'].page_range
        return kwargs

在我的模板中,我尝试以这种方式进行分页

  THIS DOESN'T DISPLAY AT ALL
 {% if all_posts.has_previous %}
   <li><a class="pgn__prev" href="?page={{ all_posts.previous_page_number }}">Prev</a></li>
  {% endif %}

 {% for x in page_range %}
  <li><a class="pgn__num" href="?page={{ x }}">{{ x }}</a></li>
 {% endfor %}

 THIS DOESN'T DISPLAY TOO
 {% if all_posts.has_next %}
 <li><a class="pgn__next" href="?page={{ all_posts.next_page_number }}">Next</a></li>
 {% endif %}

我的{{all_posts}}上下文值= <[Post:TitlePost]> 为什么不上一个和下一个工作?

1 个答案:

答案 0 :(得分:1)

all_posts只是queryset。要检查上一页和下一页,您需要page对象,该对象作为page_obj变量传递到模板:

 {% if page_obj.has_previous %}
   <li><a class="pgn__prev" href="?page={{ page_obj.previous_page_number }}">Prev</a></li>
  {% endif %}

 {% if page_obj.has_next %}
 <li><a class="pgn__next" href="?page={{ page_obj.next_page_number }}">Next</a></li>
 {% endif %}