bhylu.com

Advertisements

Django Pagination

Pagination limits how much a response loads and gives visitors a predictable way through a result set. Order the queryset before dividing it into pages.

How it works

Paginator.get_page accepts invalid or out-of-range page input with a forgiving policy; page raises explicit exceptions instead. Choose the behaviour that fits your interface and test it. The project’s ListView uses a two-item page size for a small fixture, while real page sizes should balance readability and database cost. Large offsets can become expensive, so do not claim this simple pattern scales equally well to every dataset.

Run in the supplied local Django project

This lesson uses Django 5.2.18 LTS with Python 3.12. Download the source downloader and run node download-project.mjs http://127.0.0.1:8000 with Node 22 while previewing locally. It creates a new bhylu-django-lab folder and refuses to overwrite an existing one. After deployment, the default base is bhylu.com; until then use your local preview URL.

Inside that new folder, create a virtual environment, install requirements.txt and run the complete lesson file shown below. Every lesson creates a fresh in-memory SQLite database and temporary upload storage. It does not edit the interactive lab’s db.sqlite3 or Bhylu’s database. The visible listing below is the lesson’s core code; its complete downloaded file includes the shared bootstrap.

Django does not run in Bhylu’s current browser playground. No Apache, MySQL or global PHP configuration change is needed. See the setup lesson for the full project and commands.

Example

Run .venv\Scripts\python.exe lessons\pagination.py from the downloaded project root. Download the complete lesson file; keep it under lessons/. The project’s shared models, forms, views and fixture are prerequisites, not a hidden online runtime.

lessons/pagination.py — core code

from django.core.paginator import Paginator
paginator = Paginator(Workshop.objects.order_by("pk"), 2)
first = paginator.get_page(1)
last = paginator.get_page(99)
print(first.number, list(first.object_list.values_list("slug", flat=True)))
print(last.number, last.has_next())

Expected result

1 ['lamp-care', 'bike-punctures']
2 False

Three rows produce two pages, and the out-of-range request resolves to the final page under get_page’s policy. An application should preserve other search filters when constructing page links.

Use Django’s versioned official documentation for exact API contracts and the deployment checklist before a separate release.

Advertisements