我尝试对基于类的通用视图实现分页,并且我这样做了,它不起作用。
网址
url(r'^cat/(?P<category>[\w+\s]*)/page(?P<page>[0-9]+)/$',
CategorizedPostsView.as_view(), {'paginate_by': 3}),
视图
class CategorizedPostsView(ListView):
template_name = 'categorizedposts.djhtml'
context_object_name = 'post_list'
def get_queryset(self):
cat = unquote(self.kwargs['category'])
category = get_object_or_404(ParentCategory, category=cat)
return category.postpages_set.all()
模板
<div class="pagination">
<span class="step-links">
{% if post_list.has_previous %}
<a href="?page={{ post_list.previous_page_number }}">previous</a>
{% endif %}
<span class="current">
Page {{ post_list.number }} of {{ post_list.paginator.num_pages }}.
</span>
{% if post_list.has_next %}
<a href="?page={{ post_list.next_page_number }}">next</a>
{% endif %}
</span>
</div>
当我尝试获取http:// 127.0.0.1:8000/cat/category_name/?page=1甚至http:// 127.0.0.1:8000/cat/category_name/时,我收到404异常。
如何以正确的方式在基于类的通用视图中使用分页?
答案 0 :(得分:4)
嘿paginate_by
已经有ListView
的kwarg url(r'^cat/(?P<category>[\w+\s]*)/page(?P<page>[0-9]+)/$',
CategorizedPostsView.as_view(paginate_by=3)),
所以只需将其传入。
尝试这样的事情:
{% if is_paginated %}
<div class="pagination">
<span class="step-links">
{% if page_obj.has_previous %}
<a href="?page={{ page_obj.previous_page_number }}">previous</a>
{% endif %}
<span class="current">
Page {{ page_obj.number }} of {{ paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
<a href="?page={{ page_obj.next_page_number }}">next</a>
{% endif %}
</span>
</div>
{% endif %}
对于您的模板,您可以尝试以下内容:
{{1}}