如何在基于类的通用视图中使用分页?

2 投票
1 回答
2317 浏览
提问于 2025-04-16 22:34

我在尝试给基于类的通用视图添加分页功能,但我这样做的时候,结果并没有成功。

这是我的网址设置:

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错误。

我该如何正确地在基于类的通用视图中使用分页功能呢?

1 个回答

4

嘿,ListView已经有一个叫paginate_by的参数了,所以你只需要把它传进去就行了。

可以试试这样写:

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

撰写回答