DRY recipe on Django pagination template

By | July 1, 2016

Here is a quick recipe for Django templates, let’s say you are building a Django web which has many list views, and which has pagination, it’s wise to abstract the pagination template out to be reusable by all list view templates.

My preference is to keep all reusable templates in a partials folder, and place the pagination template in there.

{% if is_paginated %}
    <ul class="pagination">
    {% for page_num in paginator.page_range %}
        {% if page_num == page_obj.number %}
          <li class="active"><a href="#">{{ page_num }}</a></li>
        {% else %}
        <li><a href="{% url urlname page_num %}?{{ request.GET.urlencode }}">{{ page_num }}</a></li>
        {% endif %}
    {% endfor %}
{% endif %}

The pagination template is switched by the ListView populated context var is_paginated, also makes use of urlname variable to construct the page links.

Then in each list view template to include the pagination:

{% include 'partials/pagination.html' with urlname='quick-admin:listing-job-list' %}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.