Chapter 36 · Generic display views, filters, and paginationCHAPTER 36
Complete six-part pre-release for review. No new package and no migration. The event list, My events, and My registrations now answer 405 to methods other than GET and HEAD (declared changes); past events move from their own section into one ordered, filtered list (a change to Chapter 22's layout, explained in the chapter). Editing views follow in Chapter 37.
Working towards: Event-day operations (Chapter 46). Reminders sent in the background, a waitlist that offers released places, and check-in that records each attendance once. All milestones
CHAPTER THIRTY-SIX
Generic display views, filters, and pagination
Stage 5: Growing the application (Chapters 35 to 46)
Prerequisites: Chapters 9 to 35, including the Chapter 35 project with its 367 passing tests, the method tables and the answers() helper, EventDetailView and ADR-006; the event list’s “places left” filter kept in the session (Chapter 28); with_places() and the queryset methods upcoming() and past() (Chapters 19 to 22)
What you’ll build: Method tables for the three list pages, written while they are still functions; Django’s Paginator tried by hand; the event page as a DetailView; one ordered, filtered event list, twelve events to a page, with past events faded; My events and My registrations as filtered, paginated lists that show only your own records; one accessible set of page links shared by all three; and event cards in a responsive grid
Why This Matters
Otahque has been running for a while now. Sam’s community holds a meetup most weeks, and every one of them stays on the event list after it ends. Today the list page loads every event on every visit: the upcoming ones, then every past event the community has ever held, faded, in one long column. Sai’s My registrations grows by a line each month, and so does Sam’s My events. Nothing is broken yet. But each of these pages gets slower and longer with every event, and none of them helps anyone find what they came for.
Sam asks for two things. First, one list, not two: events still to come at the top, soonest first, then past events, faded, most recent first, so a visitor sees what is next without scrolling past history, and history is still there for anyone who wants it. Second, a way to narrow it: just what is on now, just what is coming, just what is over, or only events that still have places. Chapter 22 showed past events in their own section at the bottom of the same page. That served a short list well; with many pages, two sections would need two page numbers in the address, and every link would have to carry both. This chapter replaces the two sections with one ordered list and filters, and says why at each step.
Soni, who checked the first release in Chapter 34, asks the question she asked in Chapter 35: how will you know the pages still answer as they did? And one more: can a filter or a page number ever show Sai’s places to Raj, or a draft to a visitor? You will answer both with tests written before the change.
Django already has the parts. Generic display views are ready-made classes for the two most common pages there are: a list of things and one thing. A paginator cuts a list into pages. Chapter 35 taught you to read what a class does before trusting it; this chapter uses that habit on classes that do much more.
By the end of the chapter, you will be able to:
explain what ListView and DetailView do for you, and which of their methods you override;
convert a function view to a generic view, keeping its checks and declaring any change in its answers;
paginate a list with paginate_by, and predict the answer to any page number;
give a list one stable order, so no row repeats or goes missing between pages;
read filters from the address with a form, ignore bad values, and keep the filters in page links with {% querystring %};
build page links that a screen reader announces properly.
Out of scope: views that change data, and the access mixin that guards them (Chapter 37); per-event registration questions (Chapter 38); paging without reloading the page (Chapter 45); pages in the API (Chapter 51); searching by keyword or date (Chapter 56).
What problem exists? Most pages in a web application either list objects or show one. Each such view repeats the same steps: fetch the rows, maybe cut them into pages, put them in a context, render a template, or fetch one row by its number and answer 404 if there is none.
What did people do before? Wrote those steps in every function, as Otahque’s event_list and event_detail did.
What is it? Django’s ListView and DetailView are classes that already do those steps. ListView fetches a queryset, paginates it if you ask, and renders a template with the rows. DetailView fetches one object by the primary key or slug in the address, answers 404 if it does not exist, and renders it.
Why use them? You write only what is different about your page, by overriding the method that does that step. The rest is code thousands of projects already run.
Now let’s use it. Step 4 turns the event page into a DetailView; Steps 7 and 8 turn three lists into ListViews.
A generic view is built from small classes called mixins, each responsible for one part of the work; Chapter 37 looks at how they combine. Here, what matters is where each view calls code you can replace. Figure 36.1 shows the path of a GET through both views, with the methods this chapter overrides.
Figure 36.1 — Where ListView and DetailView call your code.
Table 36.1 lists the names you will meet. The hooks are the methods you override; the attributes are settings you give as class variables.
Table 36.1 — The parts of a generic display view this chapter uses
Name
What it does
model or get_queryset()
The rows to show. get_queryset() is a method, so it can read the request
get_object()
DetailView: fetch one row from get_queryset() by the number in the address, or 404
pk_url_kwarg
The name of the address's number; Django expects pk, Otahque's addresses say event_id
template_name
The template to render; without it, Django builds a name such as events/event_list.html
get_context_data()
The dictionary the template sees; call super() and add to it
object_list, event_list
ListView: the rows of this page, under a general name and one made from the model
object, event
DetailView: the one row, under both names
paginate_by
ListView: rows per page; the context gains paginator, page_obj, and is_paginated
Pages
New Tool: Paginator
What problem exists? A list of five hundred events is too long for one page and too slow to fetch at once.
What did people do before? Fetched everything and cut it in the template, which still fetches everything; or wrote LIMIT and OFFSET into each query by hand.
What is it?django.core.paginator.Paginator takes a list or a queryset and a page size. paginator.page(n) returns page n as a Page object, holding only that page’s rows, with has_next(), previous_page_number(), and so on. For a queryset it asks the database for a count and for one slice, which becomes LIMIT and OFFSET in SQL. It never fetches the rest.
Why use it? It does the arithmetic and the edge cases: the last page, an empty list, a page number that is not a number.
Now let’s use it. Step 3 runs it on thirty numbers; Step 7 gives ListView a page size and lets it call Paginator for you.
Paginator has two ways to fetch a page, and they differ in what they do with a bad number. page(n) is strict: it raises PageNotAnInteger for 'abc' and EmptyPage for a number past the end. get_page(n) is forgiving: it shows the first page for 'abc' and the last page for a number past the end. ListView uses the strict one and turns each error into a 404. It also accepts the word last. Table 36.2 shows what each address gets, for a list with three pages.
Table 36.2 — What a page number gets, three pages of events
Address
ListView (Otahque)
get_page()
?page=2
Page 2
Page 2
no page, or ?page=1
Page 1
Page 1
?page=last
Page 3
Not accepted: page 1
?page=4, ?page=999
404
Page 3
?page=0, ?page=-1
404
Page 3
?page=abc, ?page=2.0
404
Page 1
Otahque keeps ListView’s 404s. They are Django’s documented behaviour, they are simple to test, and a link that points past the end is a link that is wrong. A forgiving list would hide that. The cost is that an old link to page 5, shared before some events were removed, now finds nothing. If readers find that confusing, get_page() is one method away.
Under the Hood: what one page costs
For each page, ListView sends two queries. The first is SELECT COUNT(*), so the paginator knows how many pages there are. The second fetches the rows with LIMIT 12 OFFSET 12 for page 2: skip twelve, take twelve. The count is the same work for every page, and the offset makes the database step past the rows before the page, so a page deep in a long list costs more than page 1. For a list people click through, that is fine. For a program that walks through ten thousand rows, Chapter 51 uses a different technique, a cursor, that asks for “the twelve after this one” instead.
One order for every page
Each page is a separate query, run when that page is asked for. Two queries for the same list agree on which rows come where only if the order is complete: if two rows could come in either order, the database is free to choose differently each time. With ORDER BY starts_at, two events that start at the same moment can swap places between the query for page 1 and the query for page 2. One of them then appears twice and the other never appears. Nothing errors; a row just goes missing. The fix is to finish every order with something unique, the primary key id. Django warns about the worst case, a list with no order at all, with UnorderedObjectListWarning, but it cannot see an order that is merely incomplete.
Sam’s list needs one more thing from its order: events not yet ended first, soonest first, then ended events, latest first. That is two directions in one list. A database sorts by values, so the query first computes three values for each event with conditional expressions, Case and When, Django’s way of writing SQL’s CASE WHEN. over is 0 for an event not yet ended and 1 for one that has ended. soon is the start time, but only for events not yet ended; late is the end time, only for events that have ended. Sorting by over, then soon rising, then late falling, then id, puts every event in its place. Figure 36.2 shows the result cut into pages.
Figure 36.2 — One ordered list, cut into pages of twelve.
Filters in the address
A filter is a question the visitor asks of the list, and the natural place for it is the address: /events/?show=past can be bookmarked, shared, and opened in another tab. A form with method="get" puts its fields there. Django reads them with a Form, as it reads a POST: the form checks each value against its choices, and cleaned_data holds only values it accepted.
Two choices matter for a filter form. First, a box that is not ticked sends nothing, so “nothing ticked” and “no filter sent” look the same; Otahque treats both as “show everything”. Second, a value that is not one of the choices, from a mistyped or tampered address, makes the form invalid. For a form that changes data, that is an error to show. For a filter, it is not worth an error page: the list shows everything, and nothing is saved.
Chapter 28 kept the “places left” choice in the session, so the list remembered it. This chapter keeps that promise for both filters: when the address names a filter, the choice is saved; a plain /events/ uses the saved choice. Viewing alone still saves nothing.
Page links have to keep the filters. A link written as ?page=2 drops show=past and quietly changes the list. Django’s {% querystring %} tag, new in Django 5.1, builds the link from the current address and changes only what you name: {% querystring page=2 %} on /events/?show=past gives ?show=past&page=2.
In practice: filters people share
Situation. A community organizer posts “everything on this month” in a group chat, as a link to a filtered list.
Application. Because the filter is in the address, the link shows the same list to everyone who opens it, and a page link keeps the filter on page 2.
Consideration. An address is public. Filters must never be a way around a rule: Otahque applies “published only” and “your own records only” in the view, before any filter, so no value in the address can widen what a person may see.
Page links everyone can use
Page links are navigation, and assistive technology treats navigation as a landmark a person can jump to, if it is marked as one. Three details make page links work for a screen reader: a nav element with a label, so it is announced as “Pages, navigation”; the current page marked with aria-current="page" and shown as text, not a link to where you already are; and the gaps between numbers hidden from the screen reader, which would otherwise read “dot dot dot”. Accessibility writers differ on details, such as whether the current page should still be a link; Otahque follows the pattern in Figure 36.3. Paginator.get_elided_page_range() supplies the numbers: the first and last pages, the current page and its neighbours, and Paginator.ELLIPSIS for each gap.
Figure 36.3 — Page links that a screen reader announces properly.
Start from Chapter 35, in the folder containing manage.py, with Otahque on PostgreSQL 18, 367 passing tests, and the work committed (the last commit is “Convert the event and details pages to classes”). No package, model field, or migration changes: ordering and filtering happen in queries. The new files are events/tests/test_lists.py, registrations/tests/test_lists.py, registrations/forms.py, and two template includes, templates/includes/pagination.html and templates/includes/show.html. Both apps’ models.py, views.py, urls.py, and tests/test_methods.py change, with events/forms.py, config/helpers.py, one test in events/tests/test_events.py, the three list templates, one row template, the stylesheet source, ADR-006, and the sessions design note. The visible result: the event list, My events, and My registrations each show twelve cards to a page, with checkboxes to narrow them and page links at the bottom. The chapter’s commands were checked in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.
If you did Chapter 35’s Mini-Challenge, you have registrations/tests/test_mine.py, pinning My registrations. Step 2 writes the same table beside the others, in registrations/tests/test_methods.py, so delete test_mine.py before you start, and commit the deletion: git rm registrations/tests/test_mine.py, then git commit -m "Move My registrations' table".
The Custom Way
Before you hand pagination to ListView, run Paginator on its own, on a list of plain numbers, and watch it handle the cases a list page must handle: the last, short page; a number that is not a number; a number past the end. Step 3 does it, after Step 2 has pinned the pages’ answers.
The Django Way
Step 1: Check the starting point
Terminal
uv run python manage.py test --parallel
Output
Found 367 test(s).
Creating test database for alias 'default'...
...
Ran 367 tests in ...s
OK
Terminal
git status --short
git log --oneline -1
Output
... Convert the event and details pages to classes
Step 2: Pin the list pages’ answers
ADR-006 rule 1 says a view’s answer to every method is pinned before it changes. Three list pages will change: the event list, My events, and My registrations. Read each function’s decorators first. event_list has none, so it answers every method with the page. event_manage has login_required and then permission_required, so a visitor is sent to sign in and a member without the change_event permission gets 403, whatever the method. my_registrations has only login_required.
Open events/tests/test_methods.py. Its helpers import gains in_group, which makes a member of a group, so the line reads:
events/tests/test_methods.py
from config.helpers import answers, in_group, save_event
Add three tables above HIDDEN, after the event page’s table:
events/tests/test_methods.py
# The list pages (Chapter 36), pinned while they are still
# functions: every method gets the page, after sign-in
# where the page needs it.
EVERY = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE',
'OPTIONS', 'TRACE']
LIST = [(method, 'ok', 'ok') for method in EVERY]
SIGNED_OUT_FIRST = [
(method, 'sign in', 'ok') for method in EVERY
]
NO_PERMISSION = [(method, 'sign in', '403') for method in EVERY]
EVERY lists the eight methods; each table is built from it with a list comprehension, Python’s way of writing a list as “this, for each item in that”. LIST says every method gets the page, signed out or in. SIGNED_OUT_FIRST says a visitor is sent to sign in and a member gets the page. NO_PERMISSION says a visitor is sent to sign in and a member without permission gets 403. Then add the test class at the end of the file:
events/tests/test_methods.py
class ListPageMethodTests(TestCase):
"""The list pages' answers to each method, pinned."""
@classmethod
def setUpTestData(cls):
cls.sam = in_group('sam@example.org', 'Organizers')
cls.sai = User.objects.create_user(
'sai@example.org', display_name='Sai'
)
def check(self, path, member, table):
"""Compare the page's answers with each row."""
for method, signed_out, signed_in in table:
with self.subTest(method):
self.assertEqual(
answers(path, member, method),
(signed_out, signed_in),
)
def test_the_event_list(self):
self.check('/events/', self.sai, LIST)
def test_my_events(self):
self.check('/events/manage/', self.sam,
SIGNED_OUT_FIRST)
def test_my_events_without_permission(self):
self.check('/events/manage/', self.sai, NO_PERMISSION)
Sam is in the Organizers group, so he holds change_event; Sai is not. Now My registrations. In registrations/tests/test_methods.py, import the table you just wrote, so both apps share one definition:
registrations/tests/test_methods.py
from config.helpers import answers
from events.models import Event
from events.tests.test_methods import SIGNED_OUT_FIRST
and add a class at the end:
registrations/tests/test_methods.py
class MyRegistrationsMethodTests(TestCase):
"""My registrations' answer to each method, pinned."""
def test_my_registrations(self):
sai = verified('sai@example.org')
for method, signed_out, signed_in in SIGNED_OUT_FIRST:
with self.subTest(method):
self.assertEqual(
answers('/registrations/', sai, method),
(signed_out, signed_in),
)
Run both apps’ tests:
Terminal
uv run python manage.py test events registrations --parallel
Output
Found 266 test(s).
Creating test database for alias 'default'...
...
Ran 266 tests in ...s
OK
Green on the functions: the four new tests record today.
Step 3: The Custom Way: pages by hand
Create practice_pages.py beside manage.py. It needs no database; it sets Django up only because the paginator’s gap marker is text that can be translated, and translation reads the settings:
practice_pages.py
"""Practice: Django's Paginator on thirty numbers.
Run it once, then delete it.
"""
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'config.settings')
django.setup()
from django.core.paginator import ( # noqa: E402
EmptyPage, PageNotAnInteger, Paginator,
)
paginator = Paginator(range(1, 31), 12)
print('count', paginator.count, 'pages',
paginator.num_pages)
for number in paginator.page_range:
page = paginator.page(number)
print(number, list(page), page.has_next())
for asked in ['abc', 9]:
try:
paginator.page(asked)
except (PageNotAnInteger, EmptyPage) as error:
print(repr(asked), type(error).__name__)
print(repr(asked), 'get_page:',
paginator.get_page(asked).number)
numbers = Paginator(range(1, 201), 12).get_elided_page_range(
8, on_each_side=1, on_ends=1
)
print([str(number) for number in numbers])
Thirty numbers at twelve a page make three pages, and the last holds six. page() refuses 'abc' with PageNotAnInteger and 9 with EmptyPage; get_page() answers the same two with page 1 and page 3. The last line asks for the page links around page 8 of a 200-item list: the first page, a gap, 7, 8, 9, a gap, the last page. The gap is Paginator.ELLIPSIS, the character “…”. Delete the file. ListView does all of this for you; now you know what it does.
Step 4: The event page as a DetailView
The event page has been a View since Chapter 35, with one handler that loads the event, checks it is visible, and renders. DetailView already loads an object by its number and answers 404 if there is none; you add the visibility check where the object is fetched. In events/views.py, change the import of View:
events/views.py
from django.views.generic import DetailView
and replace the class with:
events/views.py
class EventDetailView(DetailView):
"""Show an event its viewer may see, or 404.
DetailView loads the event by the number in the address
(pk_url_kwarg); get_object() adds the visibility check
and the refused record. Methods are answered as by the
View class it replaces (D35.4).
"""
pk_url_kwarg = 'event_id'
template_name = 'events/detail.html'
def get_queryset(self):
"""Events with places_left, as the page shows it."""
return Event.objects.with_places()
def get_object(self, queryset=None):
"""Return the event, or 404 if it is hidden."""
event = super().get_object(queryset)
if not event.is_visible_to(self.request.user):
deny(self.request, Action.VIEW_EVENT, event,
hidden=True)
return event
def get_context_data(self, **kwargs):
"""Add the time, the edit link, and the panel."""
now = timezone.now()
user = self.request.user
return super().get_context_data(**kwargs) | {
'now': now,
'can_edit': self.object.can_be_edited_by(user),
} | registration_panel(self.object, user, now)
pk_url_kwarg = 'event_id' tells DetailView the address names its number event_id, as events/urls.py has since Chapter 10. get_queryset() adds places_left, which the page shows. get_object() calls the parent’s version, which fetches the event or raises 404, then refuses a hidden one with deny(), recording the attempt as before. get_context_data() adds what the old get() passed to render(); self.object is the event get() fetched. Run both apps’ tests:
Terminal
uv run python manage.py test events registrations --parallel
Output
Found 266 test(s).
Creating test database for alias 'default'...
...
Ran 266 tests in ...s
OK
The event page’s table from Chapter 35 is unchanged and green: a DetailView with only get() answers every method as the View it replaces. test_missing_event still passes too, because it asks for view_class, and the class keeps its name.
Common Error: overriding get_object() and losing the check
If you replace get_object() without calling super(), or override get() and fetch the event yourself, the visibility check in this get_object() no longer runs, and a draft’s number shows the draft. Chapter 30’s tests catch it: HIDDEN’s rows turn red. Keep every check in the one method that fetches the object.
Step 5: The list’s tests first
The new list must page, order, and filter correctly. Write that down before the code. The tests need many events, so add a helper to config/helpers.py, above in_group():
config/helpers.py
def save_events(count, first, gap=timedelta(days=1),
**changes):
"""Save count published events, gap apart from first.
Titles are numbered from 1 in start order, so a test
can read the order a page shows them in.
"""
return [
save_event(title=f'Event {n + 1:03}',
starts_at=first + n * gap, **changes)
for n in range(count)
]
The titles, Event 001 to Event 030, are numbered in start order, so a test can read a page’s order from the titles it shows. Create events/tests/test_lists.py:
events/tests/test_lists.py
"""The event list and My events, a page at a time (36)."""
import re
from datetime import timedelta
from django.contrib.auth import get_user_model
from django.contrib.sessions.models import Session
from django.test import TestCase
from django.utils import timezone
from config.helpers import in_group, save_event, save_events
from events.models import Event
User = get_user_model()
def titles(response):
"""Return the event titles a page shows, in order."""
return re.findall(r'Event \d{3}|Now on|Ended \w+',
response.content.decode())
class PageTests(TestCase):
"""Thirty upcoming events make three pages."""
@classmethod
def setUpTestData(cls):
first = timezone.now() + timedelta(days=1)
save_events(30, first)
def test_each_page(self):
for page, first, count in [(1, 'Event 001', 12),
(2, 'Event 013', 12),
(3, 'Event 025', 6),
('last', 'Event 025', 6)]:
with self.subTest(page):
shown = titles(self.client.get(
f'/events/?page={page}'
))
self.assertEqual(shown[0], first)
self.assertEqual(len(shown), count)
def test_bad_page_numbers_are_not_found(self):
for page in ['abc', '0', '-1', '4', '999', '2.0']:
with self.subTest(page):
response = self.client.get(
f'/events/?page={page}'
)
self.assertEqual(response.status_code, 404)
def test_the_current_page_is_marked(self):
response = self.client.get('/events/?page=2')
self.assertContains(response, 'aria-label="Pages"')
self.assertContains(response, 'aria-current="page"')
self.assertContains(response, '?page=3')
def test_a_fixed_number_of_queries(self):
for page in [1, 3]:
with self.subTest(page):
with self.assertNumQueries(2):
self.client.get(f'/events/?page={page}')
class OrderTests(TestCase):
"""One order: not ended, soonest first; then ended."""
@classmethod
def setUpTestData(cls):
now = timezone.now()
save_event(title='Ended early',
starts_at=now - timedelta(days=9))
save_event(title='Ended late',
starts_at=now - timedelta(days=2))
save_event(title='Now on',
starts_at=now - timedelta(hours=1))
save_events(2, now + timedelta(days=3))
def test_the_order(self):
self.assertEqual(
titles(self.client.get('/events/')),
['Now on', 'Event 001', 'Event 002',
'Ended late', 'Ended early'],
)
def test_ended_events_are_faded(self):
html = self.client.get('/events/').content.decode()
self.assertLess(html.index('Event 002'),
html.index('event-past'))
self.assertLess(html.index('event-past'),
html.index('Ended late'))
class TieTests(TestCase):
"""Thirteen events at one moment, over two pages."""
def test_no_event_repeats_or_goes_missing(self):
start = timezone.now() + timedelta(days=2)
save_events(13, start, gap=timedelta(0))
shown = (titles(self.client.get('/events/?page=1'))
+ titles(self.client.get('/events/?page=2')))
self.assertEqual(
shown, [f'Event {n:03}' for n in range(1, 14)]
)
class FilterTests(TestCase):
"""Show: On now, Upcoming, Past; and places left."""
@classmethod
def setUpTestData(cls):
now = timezone.now()
save_event(title='Ended early',
starts_at=now - timedelta(days=9))
save_event(title='Now on',
starts_at=now - timedelta(hours=1))
full = save_events(2, now + timedelta(days=3),
capacity=1)[1]
sai = User.objects.create_user(
'sai@example.org', display_name='Sai'
)
full.registrations.create(member=sai)
def shown(self, address):
return titles(self.client.get(address))
def test_each_part(self):
for show, expected in [
('ongoing', ['Now on']),
('upcoming', ['Event 001', 'Event 002']),
('past', ['Ended early'])]:
with self.subTest(show):
self.assertEqual(
self.shown(f'/events/?show={show}'),
expected,
)
def test_two_parts(self):
self.assertEqual(
self.shown('/events/?show=ongoing&show=past'),
['Now on', 'Ended early'],
)
def test_places_left_leaves_out_full_and_ended(self):
self.assertEqual(
self.shown('/events/?places=0&places=1'),
['Now on', 'Event 001'],
)
def test_a_bad_value_shows_everything(self):
response = self.client.get('/events/?show=soon')
self.assertEqual(response.status_code, 200)
self.assertEqual(len(titles(response)), 4)
self.assertFalse(Session.objects.exists())
def test_the_choice_is_remembered(self):
self.client.get('/events/?show=past&places=0')
self.assertEqual(self.shown('/events/'),
['Ended early'])
def test_page_links_keep_the_filter(self):
save_events(14, timezone.now() + timedelta(days=5))
response = self.client.get('/events/?show=upcoming')
self.assertContains(response,
'?show=upcoming&page=2')
def test_nothing_matches(self):
Event.objects.filter(title='Ended early').delete()
response = self.client.get('/events/?show=past')
self.assertContains(response,
'No events match these filters.')
titles() finds the titles in a page’s HTML, in order. PageTests checks each page, the 404s from Table 36.2, the page links, and that pages 1 and 3 cost the same two queries, as the Under the Hood box said. OrderTests checks the one order. TieTests saves thirteen events at the same moment and checks that pages 1 and 2 together show each exactly once. FilterTests checks each part, two parts at once, the places filter, a bad value, the session, and that a page link keeps the filter: & is how & is written inside HTML. Run them:
Terminal
uv run python manage.py test events.tests.test_lists
Output
Found 14 test(s).
Creating test database for alias 'default'...
FAIL: test_bad_page_numbers_are_not_found
AssertionError: 200 != 404
FAIL: test_bad_page_numbers_are_not_found
AssertionError: 200 != 404
FAIL: test_bad_page_numbers_are_not_found [0]
AssertionError: 200 != 404
FAIL: test_bad_page_numbers_are_not_found [4]
AssertionError: 200 != 404
... (16 more like these)
Ran 14 tests in ...s
FAILED (failures=20)
Red, as it should be: the list is still one function with two sections and no pages.
Step 6: One order, and the filter form
Open events/models.py. Replace upcoming() and past() in EventQuerySet with these four methods:
events/models.py
def upcoming(self, now):
"""Events not yet ended at now, soonest first."""
return self.filter(ends_at__gt=now).order_by(
'starts_at', 'id'
)
def past(self, now):
"""Events ended by now, the latest first."""
return self.filter(ends_at__lte=now).order_by(
'-ends_at', '-id'
)
def showing(self, parts, now):
"""Events in the ticked parts; none ticked is all.
parts holds 'ongoing', 'upcoming', or 'past'.
"""
wanted = models.Q()
if 'ongoing' in parts:
wanted |= models.Q(starts_at__lte=now,
ends_at__gt=now)
if 'upcoming' in parts:
wanted |= models.Q(starts_at__gt=now)
if 'past' in parts:
wanted |= models.Q(ends_at__lte=now)
return self.filter(wanted)
def in_list_order(self, now):
"""Not yet ended, soonest first; then ended, latest.
over is 0 or 1; soon and late hold a time only in
their own group, so each sort key orders one group.
"""
ended = models.Q(ends_at__lte=now)
return self.annotate(
over=models.Case(
models.When(ended, then=1), default=0
),
soon=models.Case(models.When(
~ended, then=models.F('starts_at'))),
late=models.Case(models.When(
ended, then=models.F('ends_at'))),
).order_by(
'over',
models.F('soon').asc(nulls_last=True),
models.F('late').desc(nulls_last=True),
'id',
)
upcoming() and past() keep their meaning and gain id as the last thing to sort by. showing() builds one condition from the parts that are ticked: a Q object is a condition you can combine, and |= joins one more with “or”. An empty Q() matches every row, which is how “nothing ticked” shows everything. “On now” means started and not yet ended; “Upcoming” means not yet started; “Past” means ended. Every event is in exactly one part. in_list_order() is the order of Figure 36.2: annotate() adds the three computed values to each row, and order_by() sorts by them. F('soon').asc(nulls_last=True) sorts rising, with empty values at the end, so the ended events, whose soon is empty, do not interfere with the ones still to come.
Then the form. Add two classes at the end of events/forms.py:
events/forms.py
class PartsForm(forms.Form):
"""Checkboxes that narrow a list, read from the address.
Nothing ticked means everything. A value that is not
one of the choices makes the form invalid, and the list
then shows everything: a bad address is not an error.
"""
show = forms.MultipleChoiceField(
label='Show', required=False,
widget=forms.CheckboxSelectMultiple,
)
def parts(self):
"""Return the ticked parts; [] for all or invalid."""
if self.is_bound and self.is_valid():
return self.cleaned_data['show']
return []
def ticked(self):
"""Return the parts to show ticked on the page."""
return self.parts() or [
value for value, label
in self.fields['show'].choices
]
class EventFilterForm(PartsForm):
"""The event list's filters (Chapters 28 and 36)."""
places = forms.ChoiceField(
choices=[('0', 'All events'),
('1', 'Only events with places left')],
required=False,
)
def __init__(self, *args, **kwargs):
"""Name the event list's parts."""
super().__init__(*args, **kwargs)
self.fields['show'].choices = [
('ongoing', 'On now'),
('upcoming', 'Upcoming'),
('past', 'Past'),
]
def places_only(self):
"""Whether to show only events with places left."""
return (self.is_bound and self.is_valid()
and self.cleaned_data['places'] == '1')
PartsForm is a filter for any list: one field, show, a MultipleChoiceField drawn as checkboxes by CheckboxSelectMultiple. Its choices are set by each list’s form. parts() returns what was ticked, or nothing if the form was not sent or a value was bad. ticked() returns what the page should show ticked: everything, when nothing was chosen. EventFilterForm names the event list’s three parts and adds places, which keeps Chapter 28’s values, 0 and 1. Try the order on your own events with a short script, practice_order.py, beside manage.py:
practice_order.py
"""Practice: the list's order and filters on your data.
Run it once, then delete it.
"""
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'config.settings')
django.setup()
from django.utils import timezone # noqa: E402
from events.models import Event # noqa: E402
now = timezone.now()
events = Event.objects.published()
for parts in [[], ['upcoming'], ['past']]:
shown = events.showing(parts, now).in_list_order(now)
print(parts or 'all', [(e.over, e.title) for e in shown])
Your events will differ, but the shape will not: every 0 comes before every 1, events still to come are soonest first, and ended events latest first. Delete the file.
Step 7: EventListView
Now the view. In events/views.py, import ListView too:
events/views.py
from django.views.generic import DetailView, ListView
def page_numbers(page):
"""Return the page numbers a list links to.
The first and last pages, the current page and one each
side; gaps show as an ellipsis (Paginator.ELLIPSIS).
"""
return page.paginator.get_elided_page_range(
page.number, on_each_side=1, on_ends=1
)
def list_filters(request):
"""Return the event list's filter form, bound.
If the address names a filter, a valid choice is saved
in the session; a bare /events/ uses the saved choice.
Viewing alone saves nothing (Chapter 28).
"""
session = request.session
if 'show' in request.GET or 'places' in request.GET:
sent = EventFilterForm(request.GET)
if sent.is_valid():
session['event_parts'] = sent.cleaned_data['show']
session['places_only'] = sent.places_only()
return EventFilterForm({
'show': session.get('event_parts', []),
'places': '1' if session.get('places_only') else '0',
})
class EventListView(ListView):
"""Published events, twelve to a page (Chapter 36).
Events not yet ended come first, soonest first; ended
events follow, the latest first, shown faded.
"""
template_name = 'events/list.html'
paginate_by = 12
def get(self, request, *args, **kwargs):
"""Read the filters, then let ListView do the rest."""
self.now = timezone.now()
self.form = list_filters(request)
return super().get(request, *args, **kwargs)
def get_queryset(self):
"""Return the filtered events in the list's order."""
events = Event.objects.published().with_places()
events = events.showing(self.form.parts(), self.now)
if self.form.places_only():
events = events.filter(ends_at__gt=self.now,
places_left__gt=0)
return events.in_list_order(self.now)
def get_context_data(self, **kwargs):
"""Add the filter form and the time it is now."""
context = super().get_context_data(**kwargs)
return context | {
'form': self.form,
'now': self.now,
'page_numbers': page_numbers(context['page_obj']),
}
page_numbers() asks the paginator for the numbers around the current page, one on each side and one at each end. list_filters() is Chapter 28’s session code, grown: if the address names a filter and the form accepts it, the choice is saved; then the form is built from what is saved. A visit with no filter in the address reads the session but writes nothing. EventListView overrides get() to read the filters once, before ListView calls get_queryset(). get_queryset() starts from published events, so no filter can reach a draft. “Only events with places left” leaves out ended events too, because an ended event has no places to take. paginate_by = 12 is all ListView needs to page; get_context_data() adds the form, the time, and the page numbers to what ListView put there.
Two includes, shared by every list. templates/includes/show.html draws the show checkboxes from the form’s choices:
templates/includes/show.html
<fieldset class="filter-parts">
<legend class="font-semibold">Show</legend>
{% for value, label in form.fields.show.choices %}
<label class="flex items-center gap-2">
<input type="checkbox" name="show" value="{{ value }}"
class="checkbox checkbox-sm"
{% if value in form.ticked %}checked{% endif %}>
{{ label }}
</label>
{% endfor %}
</fieldset>
templates/includes/pagination.html draws the page links of Figure 36.3:
templates/includes/pagination.html
{% if page_obj.has_other_pages %}
<nav class="pagination" aria-label="Pages">
<ul class="pagination-list">
{% if page_obj.has_previous %}
{% with number=page_obj.previous_page_number %}
<li><a class="btn btn-sm" rel="prev"
href="{% querystring page=number %}"
>Previous</a></li>
{% endwith %}
{% endif %}
{% for number in page_numbers %}
{% if number == page_obj.number %}
<li><span class="btn btn-sm btn-primary"
aria-current="page">{{ number }}</span></li>
{% elif number == page_obj.paginator.ELLIPSIS %}
<li><span aria-hidden="true">{{ number }}</span></li>
{% else %}
<li><a class="btn btn-sm"
href="{% querystring page=number %}"
aria-label="Page {{ number }}"
>{{ number }}</a></li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
{% with number=page_obj.next_page_number %}
<li><a class="btn btn-sm" rel="next"
href="{% querystring page=number %}"
>Next</a></li>
{% endwith %}
{% endif %}
</ul>
</nav>
{% endif %}
page_obj.has_other_pages hides the whole nav when everything fits on one page. Each link is built by {% querystring %}, so it keeps show and places. {% with %} gives the previous and next numbers a short name, which keeps the lines short. Replace events/templates/events/list.html with:
events/templates/events/list.html
{% extends "base.html" %}
{% block title %}Events | Otahque{% endblock %}
{% block content %}
<h1>Events</h1>
<form method="get" class="filters">
{% include "includes/show.html" %}
<input type="hidden" name="places" value="0">
<label class="flex items-center gap-2">
<input type="checkbox" name="places" value="1"
class="checkbox checkbox-sm"
{% if form.places_only %}checked{% endif %}>
Only events with places left
</label>
<button type="submit" class="btn btn-sm">Filter</button>
</form>
{% if form.places_only %}
<p class="filter-note text-sm">
Showing only events with places left.
<a href="?places=0">Show all</a></p>
{% endif %}
{% regroup page_obj by over as groups %}
{% for group in groups %}
{% if group.grouper %}
<h2 class="list-heading mt-8">Past events</h2>
{% endif %}
<ul class="event-list event-cards
{% if group.grouper %}event-past{% endif %}">
{% for event in group.list %}
{% partialdef event-row inline %}
<li class="event-row event-card">
<a class="event-title"
href="{% url 'events:detail' event.id %}">
{{ event.title }}
</a>
<span class="text-sm">
{% include "events/when.html" %}
</span>
<span class="event-badges">
{% if event.starts_at <= now %}
{% if now < event.ends_at %}
<span class="badge badge-primary">
Happening now
</span>
{% endif %}
{% endif %}
{% if now < event.ends_at %}
{% include "events/places.html" %}
{% endif %}
</span>
</li>
{% endpartialdef %}
{% endfor %}
</ul>
{% empty %}
<p class="event-empty event-card">
{% if form.parts or form.places_only %}
No events match these filters.
{% else %}
No upcoming events.
{% endif %}
</p>
{% endfor %}
{% include "includes/pagination.html" %}
{% endblock %}
{% regroup page_obj by over as groups %} splits the page’s events where over changes, so a page that reaches past events shows the “Past events” heading once, at the right place, and the faded group. The row keeps its partialdef, which Chapter 12’s partial test renders on its own. Run the list’s tests:
Terminal
uv run python manage.py test events.tests.test_lists
Output
Found 14 test(s).
Creating test database for alias 'default'...
...
Ran 14 tests in ...s
OK
Green. Now the method tables, and everything else:
Terminal
uv run python manage.py test events registrations --parallel
Output
Found 280 test(s).
Creating test database for alias 'default'...
ERROR: test_event_list
AttributeError: module 'events.views' has no attribute
'event_list'
FAIL: test_the_event_list [POST]
AssertionError: ('405 GET, HEAD, OPTIONS', '405 GET, HEAD,
OPTIONS') != ('ok', 'ok')
FAIL: test_the_event_list [PUT]
AssertionError: ('405 GET, HEAD, OPTIONS', '405 GET, HEAD,
OPTIONS') != ('ok', 'ok')
FAIL: test_the_event_list [PATCH]
AssertionError: ('405 GET, HEAD, OPTIONS', '405 GET, HEAD,
OPTIONS') != ('ok', 'ok')
... (3 more like these)
Ran 280 tests in ...s
FAILED (failures=6, errors=1)
Two kinds of red, both expected. The event list’s table: as a ListView with only get(), it now answers 405 to POST, PUT, PATCH, DELETE, and TRACE, and OPTIONS itself, exactly as the event page did in Chapter 35. The function never chose its answers to those methods, so ADR-006 rule 3 applies: accept Django’s and declare them. And test_event_list names the old function. In events/tests/test_methods.py, change the list’s row:
events/tests/test_methods.py
LIST = PUBLISHED
The list answers exactly as the event page does, so the table is the event page’s table. In events/tests/test_events.py, test_event_list asks for the class, as Chapter 35’s test_missing_event does:
uv run python manage.py test events registrations --parallel
Output
Found 280 test(s).
Creating test database for alias 'default'...
...
Ran 280 tests in ...s
OK
The Chapter 28 tests passed without a change: ?places=1 and ?places=0 still work, and the session still remembers.
Step 8: My events and My registrations
The member pages get the same treatment, with one difference that matters more than any other: each must show only the signed-in member’s own records. The filter narrows that set; it never widens it.
First the queries. In events/models.py, add a method above with_places():
events/models.py
def organized_parts(self, parts, now):
"""My events in the ticked parts; none is all.
parts holds 'draft', 'published', 'cancelled', or
'past'; an ended event counts only as past.
"""
ended = models.Q(ends_at__lte=now)
wanted = models.Q()
for status in ('draft', 'published', 'cancelled'):
if status in parts:
wanted |= models.Q(status=status) & ~ended
if 'past' in parts:
wanted |= ended
return self.filter(wanted)
and finish organized_by()’s order with id:
events/models.py
).order_by('rank', 'starts_at', 'id')
In registrations/models.py, add two methods to RegistrationQuerySet, above with_people():
registrations/models.py
def showing(self, parts, now):
"""Places in the ticked parts; none ticked is all.
parts holds 'registered', 'cancelled', or 'past';
a place at an ended event counts only as past.
"""
ended = models.Q(event__ends_at__lte=now)
wanted = models.Q()
if 'registered' in parts:
wanted |= models.Q(status='active') & ~ended
if 'cancelled' in parts:
wanted |= models.Q(status='cancelled') & ~ended
if 'past' in parts:
wanted |= ended
return self.filter(wanted)
def in_list_order(self, now):
"""Order places: held ones to come first, then the rest.
Held places at events not yet ended come soonest
first; the rest follow, the latest first.
"""
current = (models.Q(status='active')
& models.Q(event__ends_at__gt=now))
return self.annotate(
earlier=models.Case(
models.When(current, then=0), default=1
),
soon=models.Case(models.When(
current, then=models.F('event__starts_at'))),
late=models.Case(models.When(
~current, then=models.F('event__starts_at'))),
).order_by(
'earlier',
models.F('soon').asc(nulls_last=True),
models.F('late').desc(nulls_last=True),
'-registered_at', '-id',
)
The registration order keeps My registrations’ two groups from Chapter 31: places held at events still to come, soonest first, then everything else, latest first. A place at an ended event counts only as past, so the parts never overlap.
Two forms. Add My events’ at the end of events/forms.py:
class MyEventsView(PermissionRequiredMixin, ListView):
"""My events: what this member organizes now.
PermissionRequiredMixin sends a visitor to sign in and
refuses a member without change_event with 403, as the
two decorators did.
"""
permission_required = 'events.change_event'
template_name = 'events/manage.html'
paginate_by = 12
def get(self, request, *args, **kwargs):
"""Read the ticked parts from the address."""
self.now = timezone.now()
self.form = MyEventsForm(request.GET or None)
return super().get(request, *args, **kwargs)
def get_queryset(self):
"""Return this member's events in the ticked parts."""
return Event.objects.organized_by(
self.request.user
).organized_parts(
self.form.parts(), self.now
).with_places()
def get_context_data(self, **kwargs):
"""Add the filter form."""
context = super().get_context_data(**kwargs)
return context | {
'form': self.form,
'page_numbers': page_numbers(context['page_obj']),
}
PermissionRequiredMixin does the work of both decorators. Before any handler runs, it checks permission_required. A visitor who is not signed in is sent to sign in; a signed-in member without the permission gets 403. Its filter form is bound only when the address has something in it: request.GET or None gives None for a plain visit, so the form is unbound and everything shows. get_queryset() starts from organized_by(self.request.user), this member’s events, before any filter.
Common Error: raise_exception=True on the mixin
The decorator said permission_required('events.change_event', raise_exception=True), and copying that to the mixin looks right. It is not. On the mixin, raise_exception = True applies to every refusal, including “not signed in”, so a visitor gets 403 instead of the sign-in page. Without it, the mixin already raises 403 for a signed-in member, because sending someone who is signed in to the sign-in page would only loop. Step 8’s table catches the mistake in the signed-out column.
Then registrations/views.py. Its imports gain the mixin, ListView, the form, and page_numbers():
registrations/views.py
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ValidationError
from django.shortcuts import (
get_object_or_404, redirect, render,
)
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views import View
from django.views.generic import ListView
from django.views.decorators.http import (
require_http_methods, require_POST,
)
from accounts.forms import PhoneForm
from audit.models import AuditEvent
from events.models import REASONS, Event
from events.views import deny, page_numbers
from .forms import MyPlacesForm
from .models import Registration
Replace my_registrations with:
registrations/views.py
class MyRegistrationsView(LoginRequiredMixin, ListView):
"""The signed-in member's places, twelve to a page.
Places held at events to come are listed first, soonest
first; the rest follow, the latest first.
"""
template_name = 'registrations/mine.html'
paginate_by = 12
def get(self, request, *args, **kwargs):
"""Read the ticked parts from the address."""
self.now = timezone.now()
self.form = MyPlacesForm(request.GET or None)
return super().get(request, *args, **kwargs)
def get_queryset(self):
"""Return this member's places, never anyone else's."""
return self.request.user.registrations.select_related(
'event'
).showing(
self.form.parts(), self.now
).in_list_order(self.now)
def get_context_data(self, **kwargs):
"""Add the filter form and the time it is now."""
context = super().get_context_data(**kwargs)
return context | {
'form': self.form,
'now': self.now,
'page_numbers': page_numbers(context['page_obj']),
}
LoginRequiredMixin is the class form of login_required. self.request.user.registrations is the member’s own places, the same reverse relation the function used, so another member’s places cannot appear whatever the address says. In registrations/urls.py:
The two templates. Replace events/templates/events/manage.html with:
events/templates/events/manage.html
{% extends "base.html" %}
{% block title %}My events | Otahque{% endblock %}
{% block content %}
<h1>My events</h1>
<form method="get" class="filters">
{% include "includes/show.html" %}
<button type="submit" class="btn btn-sm">Filter</button>
</form>
<ul class="event-list event-cards">
{% for event in page_obj %}
<li class="event-row event-card">
<p>
<a class="event-title"
href="{{ event.get_absolute_url }}">
{{ event.title }}</a>
{% if event.status == 'draft' %}
<span class="badge badge-outline">Draft</span>
{% elif event.status == 'published' %}
<span class="badge badge-primary">
Published</span>
{% else %}
<span class="badge badge-error">Cancelled</span>
{% endif %}
</p>
<p class="text-sm">
{% include "events/when.html" %}</p>
<p class="flex flex-wrap items-center gap-4 text-sm">
<a href="{% url 'events:edit' event.pk %}">Edit</a>
<a href="{% url 'events:copy' event.pk %}">Copy</a>
{% if event.status == 'draft' %}
<a href="{% url 'events:delete' event.pk %}">
Delete</a>
{% endif %}
</p>
</li>
{% empty %}
<li class="event-empty event-card">
{% if form.parts %}
No events match these filters.
{% else %}
You do not organize any events yet.
{% endif %}
</li>
{% endfor %}
</ul>
{% include "includes/pagination.html" %}
<p><a href="{% url 'events:create' %}">New event</a></p>
{% endblock %}
and registrations/templates/registrations/mine.html with:
registrations/templates/registrations/mine.html
{% extends "base.html" %}
{% block title %}My registrations | Otahque{% endblock %}
{% block content %}
<h1>My registrations</h1>
<form method="get" class="filters">
{% include "includes/show.html" %}
<button type="submit" class="btn btn-sm">Filter</button>
</form>
{% regroup page_obj by earlier as groups %}
{% for group in groups %}
{% if group.grouper %}
<h2 class="list-heading mt-8">Earlier and cancelled</h2>
{% else %}
<h2 class="list-heading">Upcoming</h2>
{% endif %}
<ul class="event-cards">
{% for place in group.list %}
{% include "registrations/row.html" %}
{% endfor %}
</ul>
{% empty %}
<p class="event-card">
{% if form.parts %}
No places match these filters.
{% else %}
No places yet.
<a href="{% url 'events:list' %}">Find an event</a>.
{% endif %}
</p>
{% endfor %}
{% include "includes/pagination.html" %}
{% endblock %}
My registrations keeps its two headings, “Upcoming” and “Earlier and cancelled”, grouped by the earlier value the order computed. In registrations/templates/registrations/row.html, the first line becomes a card:
registrations/templates/registrations/row.html
<li class="event-card">
Tests for both pages. Add a class at the end of events/tests/test_lists.py:
events/tests/test_lists.py
class MyEventsTests(TestCase):
"""My events lists only this member's, by part."""
@classmethod
def setUpTestData(cls):
now = timezone.now()
cls.sam = in_group('sam@example.org', 'Organizers')
raj = in_group('raj@example.org', 'Organizers')
events = save_events(14, now + timedelta(days=1))
for event in events[:13]:
event.add_organizer(cls.sam)
events[13].add_organizer(raj)
draft = save_event(title='Event 900',
status=Event.Status.DRAFT,
starts_at=now + timedelta(days=30))
draft.add_organizer(cls.sam)
ended = save_event(title='Ended early',
starts_at=now - timedelta(days=9))
ended.add_organizer(cls.sam)
def setUp(self):
self.client.force_login(self.sam)
def test_only_this_members_events(self):
shown = (titles(self.client.get('/events/manage/'))
+ titles(self.client.get(
'/events/manage/?page=2')))
self.assertEqual(len(shown), 15)
self.assertNotIn('Event 014', shown)
def test_each_part(self):
for show, expected in [
('draft', ['Event 900']),
('past', ['Ended early'])]:
with self.subTest(show):
self.assertEqual(
titles(self.client.get(
f'/events/manage/?show={show}'
)),
expected,
)
Raj organizes Event 014; Sam must never see it, on either page. Create registrations/tests/test_lists.py:
registrations/tests/test_lists.py
"""My registrations, a page at a time (Chapter 36)."""
import re
from datetime import timedelta
from django.test import TestCase
from django.utils import timezone
from config.helpers import save_event, save_events
from registrations.models import Registration
from .test_registrations import verified
def titles(response):
"""Return the event titles a page shows, in order."""
return re.findall(r'Event \d{3}|Ended \w+',
response.content.decode())
class MyRegistrationsTests(TestCase):
"""Only this member's places, by part and in order."""
@classmethod
def setUpTestData(cls):
now = timezone.now()
cls.sai = verified('sai@example.org')
raj = verified('raj@example.org')
events = save_events(14, now + timedelta(days=1))
for event in events[:13]:
Registration.objects.create(event=event,
member=cls.sai)
Registration.objects.create(event=events[13],
member=raj)
Registration.objects.filter(
event=events[0]
).update(status='cancelled',
cancelled_at=timezone.now())
ended = save_event(title='Ended early',
starts_at=now - timedelta(days=9))
Registration.objects.create(event=ended,
member=cls.sai)
def setUp(self):
self.client.force_login(self.sai)
def test_only_this_members_places(self):
shown = (titles(self.client.get('/registrations/'))
+ titles(self.client.get(
'/registrations/?page=2')))
self.assertEqual(len(shown), 14)
self.assertNotIn('Event 014', shown)
def test_held_places_first_then_the_rest(self):
shown = titles(self.client.get('/registrations/'))
self.assertEqual(shown[:2], ['Event 002', 'Event 003'])
shown = titles(self.client.get(
'/registrations/?page=2'
))
self.assertEqual(shown, ['Event 001', 'Ended early'])
def test_each_part(self):
for show, expected in [
('cancelled', ['Event 001']),
('past', ['Ended early'])]:
with self.subTest(show):
self.assertEqual(
titles(self.client.get(
f'/registrations/?show={show}'
)),
expected,
)
def test_a_fixed_number_of_queries(self):
for page in [1, 2]:
with self.subTest(page):
with self.assertNumQueries(7):
self.client.get(
f'/registrations/?page={page}'
)
Sai holds thirteen places, one cancelled, and one at an ended event; Raj holds one. The order test reads both pages: twelve held places first, then the cancelled one and the ended one. Run both apps:
Terminal
uv run python manage.py test events registrations --parallel
Output
Found 286 test(s).
Creating test database for alias 'default'...
FAIL: test_my_events [POST]
AssertionError: ('sign in', '405 GET, HEAD, OPTIONS') !=
('sign in', 'ok')
FAIL: test_my_events [PUT]
AssertionError: ('sign in', '405 GET, HEAD, OPTIONS') !=
('sign in', 'ok')
FAIL: test_my_events [PATCH]
AssertionError: ('sign in', '405 GET, HEAD, OPTIONS') !=
('sign in', 'ok')
FAIL: test_my_events [DELETE]
AssertionError: ('sign in', '405 GET, HEAD, OPTIONS') !=
('sign in', 'ok')
... (8 more like these)
Ran 286 tests in ...s
FAILED (failures=12)
The new tests pass; the tables do not. Both pages now answer 405 to a signed-in member’s POST, PUT, PATCH, DELETE, and TRACE, and answer OPTIONS themselves, while sign-in still comes first for a visitor. This is what Chapter 35’s Mini-Challenge predicted. Accept it, as Step 7 did: in events/tests/test_methods.py, the signed-in column of SIGNED_OUT_FIRST becomes the event page’s:
events/tests/test_methods.py
SIGNED_OUT_FIRST = [
(method, 'sign in', answer)
for method, _, answer in PUBLISHED
]
and the comment above the tables says what changed:
events/tests/test_methods.py
# The list pages (Chapter 36). As functions they answered
# every method; as classes they answer as the event page
# does, after sign-in where the page needs it.
NO_PERMISSION did not change: the mixin refuses before any handler is looked for, as the decorator did.
Terminal
uv run python manage.py test events registrations --parallel
Output
Found 286 test(s).
Creating test database for alias 'default'...
...
Ran 286 tests in ...s
OK
Step 9: Cards, filters, and page links
The lists work, but they still look like Chapter 31’s: full-width boxes, one under another. On a wide screen that wastes most of the page, and on a phone the page links are small targets. Add the styles in static/otahque/source.css, inside @layer components, above .form-actions:
.event-cards is a grid: one column on phones, two from 40rem (640 px), three from 64rem (1024 px). Every card is the same shape, with the title, the time, and the badges stacked. Ended events fade to 60% opacity, which still leaves their text readable. The filter row wraps instead of running off a phone’s screen. Each page link is at least 2.75rem (44 px) square, the size WCAG 2.2’s enhanced target-size criterion asks for, comfortable for a thumb. Build the stylesheet:
Terminal
npm run build
Run the server and look at /events/ at a phone width and a desktop width, as in Figure 36.4. Tick only “Past” and filter: the address shows ?show=past&places=0, the list shows only ended events, and if there is a second page, its link keeps show=past.
Figure 36.4 — The event list at 1280 and 390 pixels, after Step 9.
Step 10: Record, check, and commit
ADR-006 listed these views as “ListView in 36” and “DetailView in 36”. Record what happened, without rewriting the original decision. Add a section at the end of docs/adr/ADR-006-views.md:
docs/adr/ADR-006-views.md
## Update, Chapter 36
Four views converted, each after its method table:
- event_list became EventListView (ListView), one
filtered list a page at a time; it now answers 405
to methods other than GET and HEAD (rule 3).
- EventDetailView became a DetailView; its table did
not change.
- event_manage became MyEventsView (ListView with
PermissionRequiredMixin). The mixin replaces the two
decorators and gives the same answers: sign in for a
visitor, 403 for a member without change_event. Rule
2 is read as "the decorators, or a mixin the table
shows answers the same".
- my_registrations became MyRegistrationsView
(ListView with LoginRequiredMixin).
The sessions design note from Chapter 28 says what the session holds. In docs/design/sessions-and-time-zones.md, the session row now reads:
docs/design/sessions-and-time-zones.md
- django_session row: who is signed in, places_only,
and event_parts (Chapter 36). Two weeks from the last
change.
and the places filter section ends:
docs/design/sessions-and-time-zones.md
- Signing out flushes the session, and the filter with
it. An expired session is the same as none.
- Chapter 36: the list's form also sends show (On now,
Upcoming, Past), saved as event_parts. The filters are
in the address, so a filtered page can be shared; a
plain /events/ uses the saved choice. A value that is
not a choice is ignored and nothing is saved.
Run every check, then commit:
Terminal
uv run python check.py
Output
== python manage.py check
System check identified no issues (0 silenced).
== python manage.py makemigrations --check --dry-run
== python manage.py test --parallel
Found 391 test(s).
System check identified no issues (0 silenced).
Ran 391 tests in ...s
OK
== all checks passed
Terminal
git add .
git status --short
git commit -m "Page and filter the event lists"
Output
M config/helpers.py
M docs/adr/ADR-006-views.md
M docs/design/sessions-and-time-zones.md
M events/forms.py
M events/models.py
M events/templates/events/list.html
M events/templates/events/manage.html
M events/tests/test_events.py
A events/tests/test_lists.py
M events/tests/test_methods.py
M events/urls.py
M events/views.py
A registrations/forms.py
M registrations/models.py
M registrations/templates/registrations/mine.html
M registrations/templates/registrations/row.html
A registrations/tests/test_lists.py
M registrations/tests/test_methods.py
M registrations/urls.py
M registrations/views.py
M static/otahque/site.css
M static/otahque/source.css
A templates/includes/pagination.html
A templates/includes/show.html
[main 1a2b3c4] Page and filter the event lists
24 files changed, 998 insertions(+), 145 deletions(-)
create mode 100644 events/tests/test_lists.py
create mode 100644 registrations/forms.py
create mode 100644 registrations/tests/test_lists.py
create mode 100644 templates/includes/pagination.html
create mode 100644 templates/includes/show.html
If something goes wrong
Table 36.3 — Recovery for Chapter 36
Symptom
Likely cause
Recovery
TemplateDoesNotExist: events/event_list.html
template_name missing on the class
Add template_name = 'events/list.html'
The event page answers 404 for every event
pk_url_kwarg missing; DetailView looks for pk
Add pk_url_kwarg = 'event_id'
A draft's page shows the draft
get_object() overridden without the check
Call super(), then deny() for a hidden event
UnorderedObjectListWarning in the test output
A list with no order_by()
Finish the order with id
A row appears on two pages
Order ends on a value two rows share
Add id as the last thing to sort by
Page 2 loses the filter
A link written as ?page=2 by hand
Use {% querystring page=number %}
TemplateSyntaxError: Invalid block tag 'querystring'
Django older than 5.1
uv run python -c "import django; print(django.get_version())" must show 6.1
A visitor gets 403 on My events
raise_exception = True on the mixin
Remove it; the mixin sends visitors to sign in
The page links are missing
Everything fits on one page
Expected: has_other_pages is false
Anything else
A step's listing differs from yours
git diff shows your changes; git restore FILE returns a file to the last commit
Work through Table 36.4 from the folder that holds manage.py.
Table 36.4 — Verification checklist for Chapter 36
Check
Command or action
Expected result
Starting point
test --parallel
Found 367 test(s); OK
Tables first
test events registrations --parallel, after Step 2
Found 266 test(s); OK
The Custom Way
uv run python practice_pages.py
count 30 pages 3; page() refuses abc and 9; get_page() answers 1 and 3
Event page as a DetailView
Same tests, after Step 4
OK; the event page's table unchanged
List tests first
test events.tests.test_lists, after Step 5
FAILED
One order
uv run python practice_order.py
Every 0 before every 1
EventListView
test events.tests.test_lists, after Step 7
Found 14 test(s); OK
Declared answers
test events registrations --parallel, after Step 7
Red, then OK with 280 tests
Member pages
Same tests, after Step 8
Red, then OK with 286 tests
UI
/events/, My events, My registrations at 390 and 1280 px
Cards in one, two, or three columns; filters wrap; no sideways scroll
All checks
uv run python check.py
== all checks passed; Ran 391 tests
Commit
git log --oneline -1
Page and filter the event lists
Not verified
macOS and Linux shells; browsers other than Edge
Chapter 64 adds CI on Linux for every push
The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 35 checkpoint with a reader’s data, against PostgreSQL 18; the project folder is shortened to ... in printed output. The screenshots were taken in Microsoft Edge, with 24 sample events added for the screenshots only and deleted afterwards.
Que. 1 Which method of DetailView should hold the event page’s visibility check, and why that one?
Flip to check your answerFold answer back
Answer. get_object(). It is the one place the event is fetched, so every path that shows an event passes through the check. A check in get() or get_context_data() could be skipped by a later override that fetches the object another way.
Que. 2 What does ListView answer to ?page=last, ?page=999, and ?page=abc on a list with three pages?
Flip to check your answerFold answer back
Answer. Page 3, then 404, then 404. last is accepted by name; 999 is a whole number past the end, so Paginator.page() raises EmptyPage; abc is not a whole number, so it raises PageNotAnInteger. ListView turns both errors into 404.
Que. 3 Why does the list’s order end with id?
Flip to check your answerFold answer back
Answer. Every other value in the order can be shared by two events: two can start or end at the same moment. Without something unique last, the database may order such events differently in the query for page 1 and the query for page 2, so one appears twice and the other never.
Que. 4 A visitor opens /events/?show=soon. What happens, and what is saved?
Flip to check your answerFold answer back
Answer. The list shows every published event, and nothing is saved. soon is not one of the choices, so EventFilterForm is invalid, list_filters() does not save it, and parts() returns nothing, which means everything.
Que. 5 Why does the “places left” filter also leave out ended events?
Flip to check your answerFold answer back
Answer. An ended event has no places anyone can take, whatever its count says. Showing it under “places left” would invite a member to register for something that is over.
Mini-Challenge
A list of thirteen events makes two pages: twelve, then one alone. ListView can fold a short last page into the one before. Set paginate_orphans = 3 on EventListView, so a last page of one to three events joins the page before it, and write a test first, in events/tests/test_orphans.py, that fifteen upcoming events make one page and sixteen make two.
Hint:paginate_orphans sits beside paginate_by. The context’s paginator knows num_pages.
Model answer: the test first:
events/tests/test_orphans.py
"""Mini-Challenge: a short last page joins the one before."""
from datetime import timedelta
from django.test import TestCase
from django.utils import timezone
from config.helpers import save_events
class OrphanTests(TestCase):
"""paginate_orphans = 3 on EventListView."""
def test_fifteen_events_make_one_page(self):
save_events(15, timezone.now() + timedelta(days=1))
response = self.client.get('/events/')
self.assertEqual(
response.context['paginator'].num_pages, 1
)
self.assertEqual(len(response.context['page_obj']), 15)
def test_sixteen_events_make_two(self):
save_events(16, timezone.now() + timedelta(days=1))
response = self.client.get('/events/')
self.assertEqual(
response.context['paginator'].num_pages, 2
)
Output
Found 2 test(s).
Creating test database for alias 'default'...
FAIL: test_fifteen_events_make_one_page
AssertionError: 2 != 1
Ran 2 tests in ...s
FAILED (failures=1)
Then one line in EventListView:
events/views.py
paginate_by = 12
paginate_orphans = 3
def get(self, request, *args, **kwargs):
"""Read the filters, then let ListView do the rest."""
Output
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s
OK
Fifteen events are twelve plus three, and three orphans join page 1. Sixteen are twelve plus four, which is more than three, so they keep their own page. Think about Table 36.2 before you keep it: with orphans, the 404 for page 2 moves. The model answer was run and then undone; the chapter’s checkpoint does not include it.
What We Learned
ListView and DetailView do the common steps of a list page and a detail page; you override the hook for what is different.
get_object() is the one place to check whether a visitor may see the object it fetches.
paginate_by makes ListView use Paginator: two queries a page, a count and one slice.
ListView answers 404 to a page number that is not a whole number or is out of range, and accepts last; get_page() would clamp instead.
A list that is paged needs a complete order: finish it with id, or rows can repeat or vanish between pages.
Case and When compute values to sort by, so one order can run two directions.
A GET form reads filters from the address; a bad value shows everything and saves nothing.
{% querystring %} builds page links that keep the filters.
Page links need a labelled nav, aria-current="page", and hidden gaps.
The member pages start from the member’s own records, before any filter.
Key terms
Use Table 36.5 to explain this chapter’s ideas in your own words.
Table 36.5 — Key terms from Chapter 36
Term
Meaning
Generic display view
A ready-made class for a list page (ListView) or a detail page (DetailView).
Hook
A method a generic view calls that you may override, such as get_queryset().
Paginator
Django's class that cuts a list into numbered pages.
Page object
One page from a paginator: its rows, its number, and its neighbours.
paginate_by
ListView's page size; turns pagination on.
Stable order
An order complete enough that every query puts rows in the same places.
Conditional expression
Case and When: a value computed per row from conditions.
Q object
A query condition that can be combined with "or" and "and" operators.
Query string
The part of an address after ?, holding names and values.
{% querystring %}
A template tag that builds a query string from the current one.
aria-current
An attribute that tells assistive technology which item is the current one.
Orphans
Rows on a short last page; paginate_orphans folds them into the page before.
Readiness checkpoint: you are ready for Chapter 37 when uv run python check.py ends with “all checks passed” and 391 tests, the event list, My events, and My registrations show twelve cards to a page with filters, a filtered page’s links keep the filter, and git log --oneline -1 shows this chapter’s commit.
Git Commit
Your Chapter 36 work was committed once, in Step 10, as “Page and filter the event lists”: the tables, the three list views and the event page’s DetailView, the order and filter methods, the forms, the templates and includes, the styles, the tests, ADR-006’s update, and the sessions note. If you kept the Mini-Challenge, commit it on its own:
Terminal
git add events/views.py events/tests/test_orphans.py
git commit -m "Fold a short last page into the one before"
These five questions rehearse the chapter at interview level, from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead, to a bug that only shows on a busy list and to paging for programs. They are extension questions, not a gate to the next chapter. Proof files are run with uv run python manage.py shell -v 0 -c "exec(open('NAME').read())" and deleted afterwards.
L1 (Junior): What does ListView do for you?
What the interviewer is testing: Do you know what the generic view does, so you know what you still have to do?
Flip to check your answerFold answer back
Perfect answer: For a GET, ListView calls get_queryset() to get the rows, then, if paginate_by is set, cuts them into pages with Paginator and picks the page named in the address, answering 404 for a page that does not exist. It builds the context with the page’s rows as object_list and under a name made from the model, such as event_list, plus paginator, page_obj, and is_paginated, and renders template_name. What it cannot know is your page’s rules: which rows a visitor may see, in what order, and what else the template needs. Those go in get_queryset() and get_context_data().
Table 36.6 — The function and the ListView
Step
event_list (function)
EventListView
Rows
Written in the view
get_queryset()
Pages
None
paginate_by = 12
Bad page
Not possible
404, from ListView
Context
Built by hand
ListView's, plus get_context_data()
Other methods
The page, for any method
405 with Allow
Behind the scenes:
ListView.get() (summary)
self.object_list = self.get_queryset()
context = self.get_context_data()
paginate_queryset(): ?page= to a Page, or 404
page_obj, paginator, is_paginated, object_list
return self.render_to_response(context)
Code proof: the event list’s context, through the test client:
Output
EventListView is a ListView
paginator Paginator
page_obj Page
is_paginated bool
object_list EventQuerySet
event_list EventQuerySet
Common mistakes:
Doing work in get_context_data() that should narrow the rows, so the paginator counts the wrong list.
Forgetting template_name, so Django looks for events/event_list.html.
Follow-up the interviewer might ask:
Where does the name event_list come from? (The model’s name, lower-cased, plus _list; context_object_name changes it.)
What is in object_list when the list is paginated? (Only the current page’s rows.)
L2 (Mid-Level): Predict what ?page=999 gets, and when a list should clamp instead
What the interviewer is testing: Can you predict the edge cases, and choose between them?
Flip to check your answerFold answer back
Perfect answer:ListView reads page from the address. 999 converts to a whole number, so it asks Paginator.page(999), which raises EmptyPage because the list has fewer pages; ListView turns that into 404. abc fails the conversion and is not last, so it is 404 too. Paginator.get_page() would instead show the last page for 999 and the first for abc. A 404 is honest and simple to test, and Otahque chose it. A list whose links are shared widely and age quickly, such as search results, might prefer to clamp, so an old link still lands somewhere.
Figure 36.5 — What ?page=999 gets from ListView.
Behind the scenes:
paginate_queryset() (summary)
page = kwargs page, or ?page=, or 1
int(page)? no: "last" -> last page; else 404
paginator.page(number)? EmptyPage -> 404
Code proof: four page numbers on your list:
Folder structure
1 200
last 200
Not Found: /events/
999 404
Not Found: /events/
abc 404
The “Not Found” lines are Django’s request log, which records every 404 while DEBUG is on.
Common mistakes:
Expecting ListView to clamp, because get_page() does.
Testing only page 1, where nothing can go wrong.
Follow-up the interviewer might ask:
How would you make ListView clamp? (Override paginate_queryset() to use paginator.get_page().)
Does a 404 for page 999 reveal anything? (Only how many pages a public list has, which its last page link shows anyway.)
L3 (Senior): Defend one filtered list over two sections
What the interviewer is testing: Can you explain a design change against an earlier decision?
Flip to check your answerFold answer back
Perfect answer: Chapter 22 showed upcoming and past events in two sections of one page. That was right for a short list. Paginated, two sections need two page numbers, ?page and ?past_page, and every link must carry both, or paging one section resets the other. One list with one order keeps one page number: events still to come first, soonest first, so the next event is always at the top of page 1, then ended events, latest first and faded, so history is still there. Filters let a visitor ask for one part when they want it. The three parts are defined so every event is in exactly one of them, which a test can prove: the counts add up to the whole.
Figure 36.6 — Why one filtered list.
Behind the scenes:
The three parts
On now starts_at <= now < ends_at
Upcoming now < starts_at
Past ends_at <= now
Code proof: the three parts against all published events:
Output
{'ongoing': 0, 'upcoming': 3, 'past': 1}
sum 4 all 4
Common mistakes:
Defining “upcoming” as “not ended”, which counts an event that is on now twice.
Changing a recorded layout without saying what changed and why.
Follow-up the interviewer might ask:
What would make you split the list again? (A page people use mainly for history, such as an archive; then it deserves its own address.)
Where else does the session still matter? (A plain /events/ uses the last filters the visitor chose, as Chapter 28 promised.)
L4 (Staff): An event appears on pages 1 and 2. Diagnose it
What the interviewer is testing: Can you find a bug that no error message names?
Flip to check your answerFold answer back
Perfect answer: Each page is its own query with its own LIMIT and OFFSET. If the order can tie, for example twelve events starting at the same moment, SQL lets the database return tied rows in any order, and it may choose differently for the two queries. Then one event lands in both slices and another in neither. Nothing fails; a row is just missing. I would check the query’s order: if it ends on a value rows can share, add the primary key last. Otahque’s in_list_order() ends with id, and TieTests saves thirteen events at one moment to prove that two pages show each once.
Figure 36.7 — Diagnosing a row repeated across pages.
Behind the scenes:
Two pages, one incomplete order
page 1: ORDER BY starts_at LIMIT 12
page 2: ORDER BY starts_at LIMIT 12 OFFSET 12
ties may come back in a different order each time
Code proof: what each order sorts by last:
Output
by start: ('starts_at',)
list order ends with: id
Common mistakes:
Testing with events at different times only, where the bug cannot appear.
Trusting UnorderedObjectListWarning, which only warns when there is no order at all.
Follow-up the interviewer might ask:
Why might it never happen on SQLite in development? (SQLite often returns ties in insertion order; PostgreSQL makes no such promise.)
Is id always enough? (It is unique, so yes for a stable order; whether it is a meaningful tie-break is a product question.)
L5 (Lead): Page numbers here, cursors in the API. Defend the difference
What the interviewer is testing: Can you match a technique to its audience and its costs?
Flip to check your answerFold answer back
Perfect answer: People read lists a page at a time and like to jump: page 1, page 7, the last page. Page numbers fit that, and their costs, a COUNT on every page and an OFFSET that makes the database step past every earlier row, are small for lists of hundreds. Programs walk lists end to end, often while rows are being added. For them, page numbers are slow deep in a long list and unreliable when rows shift: a row added at the front pushes one onto the next page twice. A cursor, “the twelve after this one”, needs no count and no offset, and new rows do not shift it, but it cannot jump to page 7. Chapter 51 gives the API cursors; the pages people use keep numbers.
Figure 36.8 — Page numbers for people, cursors for programs.
Table 36.7 — Page numbers and cursors
Question
Page numbers
Cursor
Jump to page 7
Yes
No
Cost of a deep page
Grows with the offset
Same as page 1
Rows added while paging
Can repeat or skip one
Neither
Total count
Yes, one COUNT a page
Not needed
Fits
People, in a browser
Programs, in the API
Behind the scenes:
One numbered page in SQL
SELECT COUNT(*) FROM events ...
SELECT ... ORDER BY ... LIMIT 12 OFFSET 24
Code proof: the queries behind page 1 of the list:
Output
COUNT False False
rows True False
Common mistakes:
Using page numbers for an export or a sync job, then losing rows when data changes during the run.
Removing the count to save a query, and losing the page links people use.
Follow-up the interviewer might ask:
Can a cursor work with Otahque’s list order? (Yes, if the order is complete; the cursor encodes the last row’s sort values, which is one more reason to end with id.)
When would you add an index for this? (When the order’s columns are slow to sort; Chapter 55 measures before adding one.)