11
votes

is there any way to make page display of django pagination better? I followed the [doc][1] to create it, but hoping there is simple way to organize page number display.

Currently, it shows all the pages, say I have 10 pages, then
prev 1 2 3 4 5 6 7 8 9 10 next

If there is 100, then it will show all 100, which is pretty crazy.

Is there any way simple way to display it shorter?

example:

prev 1 2 3 ... 67 ... 98, 99, 100 next (67 is the current page)

prev 1 2 3 ... 65 66 67 68 69 ... 100 next

It doesn't have to look like above examples, but just don't want it to show every single page number without limits.

Just like the doc, I created my pagination using below codes.

Template file

{% if is_paginated %}
<div id="pagination">
<ul>
    {% if page_obj.has_previous %}
        <li> <a href="?page={{page_obj.previous_page_number}}">Previous</a> </li>
    {% else %}
        <li> Previous</li>
    {% endif %}
    {% for page_number in paginator.num_pages|template_range %}
        {% ifequal page_number page_obj.number %}
            <li class="currentpage">{{page_number}}</li>
        {% else %}
            <li> <a href="?page={{page_number}}">{{page_number}}</a> </li>
        {% endifequal %}
    {% endfor %}
    {% if page_obj.has_next %}
        <li> <a href="?page={{page_obj.next_page_number}}">Next</a></li>
    {% else %}
        <li> Next </li>
    {% endif %}
</ul>
</div>
{% endif %}

Views.py

news = News.active.all().order_by("-created_at")
paginator = Paginator(news, 15)

is_paged = False
page = None

try:
    paginator.validate_number(currpage)
except (EmptyPage, InvalidPage):
    #return bad_or_missing(request, ("Invalid page number"))
    currpage = paginator.num_pages



is_paged = paginator.num_pages > 1
page = paginator.page(currpage)

ctx = RequestContext(request, {
    'all_news_list' : page.object_list,
    'is_paginated' : is_paged,
    'page_obj' : page,
    'paginator' : paginator,
    'featured_categories' : featured_categories,
})

response = render_to_response(template_name, context_instance=ctx)
return response

Thank you.

2
have you looked at the admin code? paginator there is pretty niceJerzyk

2 Answers

4
votes

I have used the "Paginator Tag" with success to achieve the style of pagination you are looking for (often called "Digg-style" pagination). Usage is explained in the article "A Recipe for Pagination in Django".

1
votes

I have used the following package, and it is nice and simple to use. https://github.com/jamespacileo/django-pure-pagination

It solves the common issue of not displaying every single page in the template, but rather showing a range.

enter image description here

The setting make such an implementation very easy:

PAGINATION_SETTINGS = {
    'PAGE_RANGE_DISPLAYED': 10,
    'MARGIN_PAGES_DISPLAYED': 2,

    'SHOW_FIRST_PAGE_WHEN_INVALID': True,
}