簡體   English   中英

如何在基於類的通用視圖中使用分頁?

[英]How to use pagination in class-based generic views?

我嘗試將分頁實現為基於類的通用視圖,但按我的方式,這是行不通的。

網址

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

如何以正確的方式在基於類的通用視圖中使用分頁?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM