Django Pagination

django pagination

Pagination allows us to distribute iterable content over multiple pages. We can then navigate to these pages with page number of previous page and next page buttons.

Paginator Class and Page Object

Django offers a Paginator class with attributes such as:

  • page(page_number): Returns page_object with given page_number
  • has_previous: True/False if previous page number exists
  • has_next: True/False if previous next number exists
  • previous_page_number: Returns previous page number
  • next_page_number: Returns next page number
  • number: Returns current page number
  • paginator.num_pages: Returns total page numbers

Firstly, import the Paginator class.

from django.core.paginator import Paginator

Now, select number of objects per page.

p = Paginator(queryset, number_of_objects_per_page)

Then, make page object with page() function.

page_object = p.page(page_number)

In order to get page number from URL request use:

page_object = p.page(request.GET.get('page'))

Lastly, return the page_object as context variable. The combined code under views.py will look as below:

    from django.core.paginator import Paginator
    def my_view_function(request):
        queryset = ['A', 'B', 'C', 'D', 'E']        # sample data
        p = Paginator(queryset, 1)                  # for 1 object per page
        try:
            page_number = request.GET.get('page')
            page_object = p.page(page_number)
        except:
            page_object = p.page(1)                 # load first page by default
        return render(request, 'my_template.html', {'page_object':page_object})
                                

Adding Pagination in Templates

To apply page effect from Paginator page_object, refer to the code below:

        {% for i in page_pbject %}
            {{i}}
        {% endfor %}}
        
        {% if page_object.has_previous %}
            href="?page={{ page_object.previous_page_number }}"
        {% endif %}
        Page {{ page_object.number }} of {{ page_object.paginator.num_pages }}
        {% if page_object.has_next %}
            href="?page={{ page_object.next_page_number }}"
        {% endif %}