简体   繁体   English

在django模板中分页有问题吗?

[英]Problem with pagination in template django?

I have such view in my application and I try to paginate in in my temlate. 我在应用程序中有这样的观点,并尝试在我的模板中进行分页。 But prev and next don't work. 但是上一个和下一个不起作用。 What's wrong? 怎么了?

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

And in my template I try to paginate such way 在我的模板中,我尝试以这种方式进行分页

  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 %}

My context value of {{all_posts}} = <[Post: TitlePost]> Why dont previous and next work? 我的{{all_posts}}上下文值= <[Post:TitlePost]>为什么上一个和下一个无效?

all_posts is just queryset. all_posts只是queryset。 To check previous and next page you need page object, which passed to the template as page_obj variable: 要检查上一页和下一页,您需要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 %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM