How to Add Pagination in Django Using Django Pagination: A Complete Guide
Django provides a built-in pagination framework centered around django.core.paginator.Paginator and integrated into class-based views via MultipleObjectMixin, allowing you to paginate any iterable with minimal configuration by setting paginate_by in your view.
Django ships with a fully-featured pagination system that powers its generic list views. Whether you're building a blog archive, an admin dashboard, or a product catalog, implementing django pagination requires only a few lines of code while leveraging robust components from django.core.paginator and django.views.generic.list.
Core Components of Django Pagination
The Paginator Class (django/core/paginator.py)
The foundation of Django's pagination system is the Paginator class located in django/core/paginator.py. This class takes any iterable (typically a QuerySet) and splits it into discrete Page objects. It handles validation of page numbers, supports orphan handling (allowing the last page to have fewer items than the limit), and raises InvalidPage exceptions for out-of-range requests.
MultipleObjectMixin Integration (django/views/generic/list.py)
For class-based views, MultipleObjectMixin in django/views/generic/list.py provides the pagination integration layer. This mixin reads the view's paginate_by attribute to determine page size, instantiates the Paginator via get_paginator(), and extracts the current page number from the URL using page_kwarg (defaulting to "page"). It returns a tuple containing (paginator, page, object_list, is_paginated).
ListView Implementation
ListView inherits from MultipleObjectMixin and completes the pagination workflow. When paginate_by is set, get_context_data() automatically injects four key variables into your template: paginator, page_obj, is_paginated, and object_list. This eliminates manual context management while maintaining full access to the underlying pagination objects.
How Pagination Works in Django's Class-Based Views
Understanding the execution flow helps debug pagination issues and customize behavior. The process follows this sequence:
ListView.get()callsget_queryset()to retrieve the full dataset.MultipleObjectMixin.get_context_data()checks ifpaginate_byis truthy.- If pagination is enabled,
paginate_queryset()instantiates aPaginatorwith the queryset and page size. - The method resolves the current page number from
request.GET.get(self.page_kwarg, 1), supporting integer strings and the special value"last". - The Paginator validates the page and returns the slice of objects, which the view adds to the context along with the paginator instance and boolean flags.
Implementing Django Pagination: Code Examples
Method 1: Class-Based Views with ListView
The most concise approach uses ListView with the paginate_by attribute. In myapp/views.py:
from django.views.generic import ListView
from .models import Article
class ArticleListView(ListView):
model = Article
template_name = "articles/list.html"
paginate_by = 10
context_object_name = "articles"
In your template articles/list.html:
{% for article in articles %}
<h2>{{ article.title }}</h2>
{% empty %}
<p>No articles found.</p>
{% endfor %}
{% if is_paginated %}
<div class="pagination">
{% if page_obj.has_previous %}
<a href="?page={{ page_obj.previous_page_number }}">« previous</a>
{% endif %}
<span>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 %}
</div>
{% endif %}
Method 2: Manual Pagination in Function-Based Views
For function-based views, instantiate Paginator directly from django/core/paginator.py. This approach gives you explicit control over error handling:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render
from .models import Article
def article_list(request):
article_list = Article.objects.all()
paginator = Paginator(article_list, 10)
page = request.GET.get("page", 1)
try:
articles = paginator.page(page)
except PageNotAnInteger:
articles = paginator.page(1)
except EmptyPage:
articles = paginator.page(paginator.num_pages)
return render(request, "articles/list.html", {
"articles": articles,
"paginator": paginator,
"page_obj": articles,
"is_paginated": paginator.num_pages > 1,
})
Method 3: Customizing the Page Query Parameter
To use a different URL parameter than page, override page_kwarg in your view class. This changes the query string from ?page=2 to ?p=2:
class CustomPageListView(ListView):
model = Article
paginate_by = 5
page_kwarg = "p"
Handling Pagination Errors and Edge Cases
The Paginator class in django/core/paginator.py raises specific exceptions for invalid inputs that you should handle in custom implementations:
InvalidPage: Base exception for all page-related errors.PageNotAnInteger: Raised when the page argument is not an integer (e.g.,?page=abc).EmptyPage: Raised when the page number exceeds the available pages.
When using class-based views, MultipleObjectMixin handles these exceptions automatically, redirecting invalid page numbers to the first or last valid page. For function-based views, explicitly catch these exceptions as shown in Method 2.
Additionally, the Paginator supports an orphans parameter. If the last page would contain fewer items than the specified orphan count, those items are rolled into the previous page, preventing near-empty final pages.
Summary
- Django pagination relies on
django.core.paginator.Paginatorto split iterables into discrete pages, handling validation and orphan control. - Class-based views leverage
MultipleObjectMixinindjango/views/generic/list.pyto automate pagination via thepaginate_byattribute. ListViewautomatically injectspaginator,page_obj,is_paginated, andobject_listinto template context.- Function-based views require manual instantiation of
Paginatorand explicit handling ofPageNotAnIntegerandEmptyPageexceptions. - Customize the URL query parameter by overriding
page_kwargin your view class.
Frequently Asked Questions
What is the difference between Paginator and Page in Django?
The Paginator class in django/core/paginator.py acts as a factory that manages the entire collection, calculating total pages and validating page numbers. A Page object represents a single slice of data returned by Paginator.page(). The Page knows its number, whether it has previous or next pages, and provides methods like has_previous() and next_page_number() for template logic.
How do I paginate a custom queryset in Django?
To paginate a custom queryset, override the get_queryset() method in your ListView subclass, then set paginate_by as usual. The MultipleObjectMixin automatically passes the returned queryset to the paginator. For function-based views, pass your filtered queryset directly to Paginator(queryset, items_per_page) before handling the page extraction.
Can I change the URL query parameter from "page" to something else?
Yes. Set the page_kwarg attribute in your class-based view to your desired parameter name. For example, setting page_kwarg = "p" changes the URL from ?page=2 to ?p=2. This value is read by MultipleObjectMixin.paginate_queryset() when resolving the current page from request.GET.
How does Django handle out-of-range page numbers?
When using class-based views, MultipleObjectMixin catches InvalidPage exceptions (including EmptyPage) and adjusts the behavior automatically: if the page number is not an integer, it defaults to page 1; if it exceeds the maximum, it returns the last page. In manual implementations using django/core/paginator.py, you must explicitly catch EmptyPage and PageNotAnInteger to handle these cases gracefully.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →