Django Pagination

Originally Posted on with tags: django
Last Update on

Merriam-Webster dictionary defines pagination as “the action of paging”. In web design world, pagination means separating a large list of contents onto different pages for easy web navigation.

Django provides a few classes that help you manage pagination. The official documentation has one page on Pagination. The source code is in one file django/core/paginator.py, which has 195 lines (version 2.2.2). The Paginator and Page classes defined in this file are very good python class examples.

The Paginator class has those public methods:

  • validate_number
  • get_page : calls page method, handles exception
  • page : page number is 1-based
  • count : cached_property
  • num_pages
  • page_range

The Page class is derived from collections.abc.Sequence, and it has those public methods:

  • has_next
  • has_previous
  • has_other_pages
  • next_page_number
  • previous_page_number
  • start_index
  • end_index

The Page class also defines __len__ and __getitem__ methods, and it has three attributes: object_list, number, and paginator.

Chapter 14 of Django Unleashed book covers how to use the django pagination in detail. An online article How to Paginate with Django is also a nice summary on how to use paginator. In class based views, all it takes is to add one line of code to use Django paginator.

paginate_by = 10

The template will be rendered with a context object with those contents:

context = {
            'paginator': paginator,
            'page_obj': page,
            'is_paginated': is_paginated,
            'object_list': queryset
        }

The context object is defined in the get_context_data method of MultipleObjectMixin. The queryset value of context dictionary is returned by paginate_queryset method, and it is page.object_list. You can easliy navigate the source code on this Class CBV website.