Search code examples
pythondjangodjango-generic-viewsdjango-pagination

How to use pagination in class-based generic views?


I try to implement pagination to class-based generic view and in way I did it, it's not works.

urls

url(r'^cat/(?P<category>[\w+\s]*)/page(?P<page>[0-9]+)/$',
    CategorizedPostsView.as_view(), {'paginate_by': 3}),

view

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()

template

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

When I try to get the http:// 127.0.0.1:8000/cat/category_name/?page=1 or even http:// 127.0.0.1:8000/cat/category_name/ I got 404 exception.

How to use pagination in class-based generic views in right way?


Solution

  • hey there is already a kwarg paginate_by for the ListView so just pass it in. try something like this:

    url(r'^cat/(?P<category>[\w+\s]*)/page(?P<page>[0-9]+)/$',
        CategorizedPostsView.as_view(paginate_by=3)),
    

    and for your template you could try something like:

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