python - 如何在基于类的通用 View 中使用分页?

标签 python django django-generic-views django-pagination

我尝试对基于类的通用 View 实现分页,但按照我的方式,它不起作用。

网址

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 异常。

如何在基于类的通用 View 中正确使用分页?

最佳答案

嘿,ListView 已经有一个 kwarg 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 %}

关于python - 如何在基于类的通用 View 中使用分页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6884752/

相关文章:

python - Apache Airflow : No module name 'airflow'

python - Django - MYSQL中自动删除 'old'数据集

python - 在 OS Mavericks 中设置/更改 PYTHONPATH

python - 如何反转多维数组中的重复值

通过API上传Django文件

django - 实现 djangorestframework-simplejwt 无密码 token 认证

Django:将过滤(和排序)添加到基于(通用)类的 ListView 的最佳方法?

python - 无法为 `pip` 安装 `python 3.3` 但对于 `python 2.7` 工作正常

python - Django 更新 View : define fields dynamically via function instead of a member variable

Django Rest Framework - 带有身份验证/权限装饰器的 GenericViewSet