2

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?

I159
  • 29,741
  • 31
  • 97
  • 132

1 Answers1

4

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 %}
darren
  • 18,845
  • 17
  • 60
  • 79
  • 1
    Thanks. And URL will be a little simpler - `url(r'^cat/(?P[\w+\s]*)/$, CategorizedPostsView.as_view(paginate_by=3)),` For get method explicit declaration of url is not necessary. – I159 Jul 31 '11 at 09:13