ContentsClose contents
Pre-release
Chapter 31 · Event registration and cancellationCHAPTER 31

Complete six-part pre-release for review. Adds django-phonenumber-field 9.0.0 and five migrations, one of which fills existing events. Two overlapping requests for the last place are proved on PostgreSQL in Chapter 33; emails follow in 43 and 44, the waitlist and check-in in 46, registration questions in 38, and the download in 41.

Working towards: First release (Chapter 34). One community runs free events. Members sign up, register, see, and cancel their registrations; organizers publish their own events; two people cannot both take the last place. Tests check each product rule. All milestones

CHAPTER THIRTY-ONE

Event registration and cancellation

Stage 4: Accounts and first release (Chapters 24 to 34)

Prerequisites: Chapters 15 to 30, including the Chapter 30 project and its 288 passing tests, the Registration model and its database rules from Chapter 21, with_places() from Chapter 22, the event states of Chapter 26, sign-in through django-allauth, and the permission matrix and audit trail of Chapter 30

What you’ll build: Registration times on every event, required before it is published; a Register button that gives a member one place, or says exactly why not; a “My registrations” page and a cancel page that releases the place once and marks a late cancellation; a phone number on the member’s profile that an event can ask for; and an attendee list, with email addresses and phone numbers, that only the event’s organizers and the administrator can open

Why This Matters

Sam’s Django clinic is published. Twenty-five people can take part, and the page says “25 of 25 places left”. Nothing else happens: there is no button. Sai wants a place, and later, on the morning of the clinic, she wants to be sure she still has one. Otahque has stored registrations since Chapter 21 and counted them since Chapter 22, but no member can make one, and no page shows one.

Places are where most of Otahque’s rules meet. A place may only be taken on a published event, while registration is open, by a member whose email address works, and only while places are left. Sai must not end up with two places by pressing the button twice. Raj, who cannot come after all, must be able to give his place back, even the evening before, and Sam must see that it came back late. Soni must be told “full” or “closed”, not shown an error. And Sai, curious, will type the number of Raj’s registration into the address bar: nothing may change, and nothing may show.

Sam has his own question. He plans the room from the list of people coming, and if the venue changes he has to reach them, so he needs their email addresses and phone numbers. That list holds personal details, so it is the most sensitive page Otahque has built: only Sam and his co-organizers, and the community’s administrator, may open it. Raj organizes the Delhi event; Sam’s list is not his to read.

By the end of the chapter, you will be able to:

  • write a business rule as a list of named reasons, and test each reason at its exact boundary;
  • add optional and required times to a model, with database rules for their order and a data migration for existing rows;
  • put an action in a model method inside a transaction, keep a database rule as the backstop, and turn only the expected database error into a friendly answer;
  • keep state-changing actions on POST, answer a repeated request with the same result, and confirm before an action that cannot be taken back;
  • show a member only their own records, and an organizer an attendee list in a fixed number of queries;
  • store a phone number in one international form with a maintained library, and tell members who will see it.

Two overlapping requests for the last place are not settled here: SQLite cannot show the problem, and Chapter 33 proves the fix on PostgreSQL. Emails to members come in Chapters 43 and 44, the waitlist and check-in in Chapter 46, per-event registration questions in Chapter 38, and the attendee list as a download in Chapter 41.

PAGE 001

What You Need to Know

Rules as named reasons

Chapter 2 wrote Otahque’s registration rules in plain words, and in November 2026 the user decided the details this chapter builds: when registration opens and closes, what happens to a late cancellation, and who may register. Table 31.1 collects them.

Table 31.1 — Registration rules this chapter builds
Rule Decision
Opening time Optional; blank means registration opens when the event is published
Closing time Required to publish; registration has closed from that instant
Cancellation deadline Required to publish; members may still cancel until the start, but later cancellations count as late
Who may register A signed-in member whose email address is confirmed
Phone number Asked for once, when an event requires it, and kept on the profile
Who sees contact details The event's current organizers and the administrator only

A rule like “you may register” is really several questions, and when the answer is no, the member deserves to know which one failed. Chapter 26 met the same need for publishing: readiness_problems() returns a list of what is missing, and an empty list means ready. This chapter does the same for registering, with one change: each reason has a short code, such as closed or full, as well as a message. Tests and views compare codes, which do not change when the wording does. Figure 31.1 shows the reasons in the order they are checked.

A blue card at the top, Sai presses Register, a POST, signed in. An arrow leads down through seven numbered purple check cards, each with an arrow to a red code card on its right: 1 Already holds a place?, already_registered; 2 Event published?, not_published; 3 Registration opened?, not_open; 4 Before the closing time?, closed; 5 A place left?, full; 6 Email address confirmed?, unverified; 7 Phone number, if asked?, phone_missing. Below the last check, a green card: a place, in one transaction, Event.register(), with the unique rule as the backstop.
Figure 31.1 — One request, seven named reasons.

The first two reasons end the list on their own. A member who already holds a place should hear “You already have a place”, not “full”; and on a draft or a cancelled event, nothing else matters. The other reasons are all collected, so a member who is both late and unconfirmed is told both.

Times at the edge

Every time rule has an edge, and the edge must be decided, not left to chance. Chapter 2 chose them: the opening time is inclusive, so a member may register at exactly that instant, and the closing time is exclusive, so at exactly that instant registration has closed. A window that includes its start and excludes its end is called half-open, written [opens, closes). Half-open windows meet without overlapping: one closing at 18:00 and the next opening at 18:00 never both apply.

The cancellation deadline works differently since the user’s decision. Cancelling is always allowed until the event starts, because a place that will not be used should go back to the pool. The deadline only decides how the cancellation is counted: before it, on time; from it on, late. Figure 31.3, in Step 7, puts the four times on one line.

Actions as model methods, inside a transaction

Chapter 22 decided where code like this lives: fat models, thin views. Reads are QuerySet methods, actions are model methods, and a view reads the request, calls one method, and answers. Registering is an action on an event, so it becomes Event.register(member, now), and cancelling an action on a place, Registration.cancel(now). Both take now, the moment the request is decided, rather than reading the clock themselves. The tests, the views, and later the API (Chapter 50) all call the same methods, so the rules cannot drift apart.

New Concept: a transaction around check and write

What problem exists? Registering is two database steps: count the places taken and check the member, then insert a row. If the second step fails, nothing from the first should remain, and nothing in between should be half-done.

What did people do before? Each step was saved on its own, and a failure in the middle left a mess to tidy by hand.

What is it? transaction.atomic() runs a block as one unit: at the end every change is kept, and on an exception every change is undone. Blocks can nest; an inner block becomes a savepoint, which can be undone without undoing the outer block.

Why use it? The check and the write succeed or fail together, and Chapter 33 can add a lock inside the same block without changing anything around it.

Now let’s use it. Step 6 writes register() with an outer block for the whole action and an inner one around the insert.

A transaction alone does not stop two requests from both counting “one place left” before either inserts. Chapter 21 already gave Otahque one rule the database enforces whatever the code does: registration_one_active, at most one active place per member and event. This chapter keeps that rule as the backstop. The method checks first and gives a readable answer; if two requests from the same member slip past the check together, the database refuses the second insert with an IntegrityError.

Catching that error needs care. Django’s transaction documentation is plain about it: do not catch database errors inside an atomic() block, because the block is then broken; wrap the risky statement in its own inner atomic() and catch the error outside that inner block. And not every IntegrityError means “already registered”. A different failure, such as a value the database refuses, must not be reported as a repeat, or a real fault would be hidden behind a friendly message. So register() looks for the member’s active place after the error: if it is there, the request was a repeat; if not, the error is raised again.

Under the Hood: what a savepoint undoes

When the inner atomic() starts, Django asks the database for a savepoint, a named mark inside the open transaction. The insert fails, and Django marks the transaction as broken (PostgreSQL does the same on its side). Leaving the inner block with an exception rolls back to the savepoint, which clears that mark and keeps everything before it. Only then may the outer block run another query, such as looking for the existing place. Catch the error without an inner block and the next query fails with TransactionManagementError, on every database, which is why the rule is “inner block, then catch”.

Safe methods, repeats, and Post/Redirect/Get

HTTP’s specification, RFC 9110, calls GET and HEAD safe: a client may send them without expecting anything to change. Browsers prefetch links, crawlers follow them, and link checkers in chat apps open them to show a preview. A “Register” link would register whoever’s browser opened it, so the specification says that an action reached by GET must be disabled. Register and Cancel are POST forms, protected by the CSRF token from Chapter 24.

POST is not idempotent: sending it twice may do two things. Browsers do not resend it on their own, but people do: a double click, the Back button, a page refreshed after a slow network lost the answer. Chapter 2 asked for these repeats to show the result the member already has. A second Register finds the place and says “You already have a place”; a second Cancel finds the place cancelled and says so. Neither writes anything. OWASP’s testing guide names this kind of check: an action that may be used once per person must be limited on the server, ideally by the database, and tested by repeating the request.

After each POST the view redirects to a page, the Post/Redirect/Get pattern from Chapter 24, so refreshing the page repeats a harmless GET, not the action. And because a released place may be taken by someone else at once, Cancel first shows a confirmation page, as Chapter 26 did for deleting a draft.

Your own records, and an organizer’s list

Chapter 30 named the risk: an IDOR is a page that finds a record by the number in its address and forgets to ask whose it is. A cancel page at /registrations/7/cancel/ is exactly such a page. The defence is the same: look the record up, compare its member with the signed-in member, and answer “not found” when they differ, so the number reveals nothing. Chapter 30’s deny() records the refused attempt.

The attendee list is the opposite case: a page that must show other people’s details, but only to a few. Its rule joins two earlier ones. Sam may open it because he is a current organizer of the event (has_organizer(), Chapter 25); the administrator may open it because the Administrators group holds registrations.view_registration (Chapter 30). Everyone else is refused with 404 when they cannot see the event at all, and 403 when they can. Figure 31.4, in Step 10, shows who sees what.

The list shows each person’s name, email, and phone, so one more rule applies: members are told before they register. The Register button carries one sentence saying that the event’s organizers will see these details. A notice is not consent to anything else; Chapter 65 deals with keeping, exporting, and removing personal data.

New Tool: django-phonenumber-field

What problem exists? Members type phone numbers in many shapes: “98765 43210”, “098765-43210”, “+91 98765 43210”. Stored as typed, the same number looks like three, and a mistyped one is only found when Sam calls it.

What did people do before? A plain text field, perhaps with a pattern that accepted digits, spaces, and a plus sign, and no idea whether the number could exist.

What is it? A Django model and form field built on phonenumbers, the Python port of Google’s libphonenumber. It reads a number, checks it against each country’s numbering plan, and stores it in E.164, the international form: a plus sign, the country code, and the number, such as +919876543210.

Why use it? One stored form, a real validity check, and readable display formats, maintained by others as countries change their plans. Version 9.0.0 declares Django 6.1 support.

Now let’s use it. Step 3 installs it and adds Profile.phone; a number typed without a country code is read as Indian, Otahque’s default region.

A valid number is not a verified one. Otahque never sends a text message, so it cannot know that the number belongs to the member: it is a contact detail the member gave, and the attendee list says no more than that.

Testing time

A test that compares with the real clock gives different answers at different times. Registration that closes “in one hour” is open when the test starts and may be closed when it ends; a test run at 23:59 meets a different day from one run at noon. Chapter 22 avoided this by passing now into upcoming(now). This chapter does the same everywhere: registration_problems(member, now), register(member, now), and cancel(now) take the moment as an argument, and the tests pass exact instants: one microsecond before closing, and exactly at closing.

Packages such as time-machine freeze Python’s clock instead. They work, but they do not change the database’s own clock, and passing now needs no package at all. The page tests still use the real clock, with events far enough away that no boundary is near.

Try it yourself

Que. 1 Registration for Sam’s clinic closes at 18:00. Soni presses Register at 17:59:59.999999, and Sai at 18:00:00. Who gets a place, if one is left?

Flip to check your answerFold answer back

Answer. Soni. The closing time is exclusive: before 18:00 registration is open, and from 18:00 it has closed. Sai is told “Registration has closed.”

Que. 2 Raj cancels at 20:00 on the evening before the clinic. The cancellation deadline was 18:00 that day, and the clinic starts at 10:00 the next morning. What happens?

Flip to check your answerFold answer back

Answer. His place is released, because cancelling is allowed until the start, and the cancellation is counted as late, because it came after the deadline. Sam’s list shows one more late cancellation, and Raj’s own page shows “Cancelled late”.

PAGE 002

How We Build It

Start from Chapter 30, in the folder containing manage.py, with your own .env, the locked environment, 288 passing tests, every migration applied, and the Organizers and Administrators groups. One package is added, django-phonenumber-field. The new files are docs/design/registration.md, registrations/urls.py, seven templates in registrations/templates/registrations/, and five migrations, one of which fills in existing events. The visible result is a Register button on each open event, a “My registrations” link in the menu, and, for organizers, an “Attendee list” link on their events. The commands are written the same for Windows PowerShell, Git Bash, macOS, Linux, and WSL; the chapter’s checks ran in the first two. Each step with new behaviour writes its tests first and runs them to see them fail.

The new tests use helpers from Chapter 30, in_group() and outcome(), and four of their own: verified() makes a member whose email address is confirmed, clinic() Sam’s published clinic with fixed times, soon() the same clinic a week from now, open for registration, and url() the address of a registrations page.

The Custom Way

The registration code in most tutorials counts the places in the view and inserts a row if there is room, often behind a link. Save this practice file as s_count.py beside manage.py, run it with uv run python manage.py shell -c "exec(open('s_count.py').read())", and delete it. It works inside a transaction that it rolls back, so your rows are unchanged:

"""Practice: the Custom Way, counting before inserting."""
from datetime import timedelta

from django.db import IntegrityError, transaction
from django.utils import timezone

from accounts.models import User
from events.models import Event


def count_then_insert(event, member, counted):
    """Insert a place if the count taken earlier had room."""
    if counted < event.capacity:
        return event.registrations.create(member=member)
    return None


with transaction.atomic():
    start = timezone.now() + timedelta(days=7)
    event = Event.objects.create(
        title='Practice clinic', starts_at=start,
        ends_at=start + timedelta(hours=1), timezone='UTC',
        location='Online', capacity=2, status='published',
    )
    a, b, c = [User.objects.create_user(
        f'{name}@example.net', display_name=name)
        for name in ('ann', 'ben', 'cal')]
    event.registrations.create(member=a)
    # Two requests arrive together; each counts first.
    seen_by_b = event.places_taken()
    seen_by_c = event.places_taken()
    count_then_insert(event, b, seen_by_b)
    count_then_insert(event, c, seen_by_c)
    print('capacity 2, places taken:', event.places_taken())
    try:
        with transaction.atomic():
            count_then_insert(event, b, 0)
    except IntegrityError:
        print('same member twice: refused by the database')
    transaction.set_rollback(True)
capacity 2, places taken: 3
same member twice: refused by the database

Two requests that count before either inserts both see room, and a clinic for two now has three places. The database refused the second place for the same member, because Chapter 21’s unique rule holds whatever the code does, but no rule limits the total. Behind a GET link the code would also run whenever a browser prefetched the link or a chat app built a preview of it. The Django Way keeps the count and the insert inside one transaction in one model method, answers only POST, and states plainly what remains open: on SQLite two overlapping requests cannot be reproduced, so the total under load is proved in Chapter 33.

The Django Way

Step 1: Check the starting point

uv run python manage.py test
Found 288 test(s).
Creating test database for alias 'default'...
...
Ran 288 tests in ...s

OK
Destroying test database for alias 'default'...
git status --short
git log --oneline -1
... Add roles, organizer access, and an audit trail

Step 2: The rules on paper

Before code, write down what Table 31.1 decided in the terms the code will use: each reason by its code, each state of a place, each page, and who sees what. Create docs/design/registration.md:

# Registration and cancellation: low-level design

Status: Drafted in Chapter 31, for review. Not approved.
Rules: PR-1 (one active place each), PR-2 (cancel your
own place; history kept), PR-3 (no more places than
capacity), PR-4 (own places; organizers see their
events' lists). Timing: Chapter 2, decided 21 November
2026.

## Registration times (on Event)

- registration_opens_at: optional; blank means open as
  soon as the event is published. Inclusive.
- registration_closes_at: needed to publish. Exclusive:
  at that instant registration has closed.
- cancellation_deadline: needed to publish. Cancelling
  stays possible until the start; from the deadline on,
  a cancellation counts as late.
- Opening before closing; closing and deadline no later
  than the start (CHECK constraints). Typed in the
  event's own zone; moved with the start by a copy.

## Who may register, and why not

Event.registration_problems(member, now) returns codes,
checked in this order. Test: RegistrationRuleTests.

| Code               | When                                   |
|--------------------|----------------------------------------|
| already_registered | member holds an active place           |
| not_published      | a draft or a cancelled event           |
| not_open           | before registration_opens_at           |
| closed             | at or after registration_closes_at     |
| full               | active places reach capacity           |
| unverified         | the account email is not confirmed     |
| phone_missing      | phone_required, and no number on file  |

No code: Event.register() makes the place, inside a
transaction. A repeat finds the place and says "You
already have a place". The unique rule
registration_one_active (code already_registered) is the
backstop; only that error is read as a repeat.

## States of a place

| State     | Counts as taken | Shown to the member      |
|-----------|-----------------|--------------------------|
| active    | yes             | You have a place         |
| cancelled | no              | Cancelled, or Cancelled  |
|           |                 | late (from the deadline) |

Lateness is worked out from cancelled_at and the
deadline; no field stores it. Registering again after
cancelling makes a new row, under the same rules.
Registration.cancel(now) changes only an active row, in
one UPDATE: a repeat changes nothing.

## Pages

- POST events/<id>/register/: Register (signed in).
- GET/POST events/<id>/register/phone/: asks once for a
  phone number, keeps it on the Profile, then registers.
- GET registrations/: My registrations.
- GET/POST registrations/<id>/cancel/: confirm, cancel.
- GET events/<id>/registrations/: the attendee list.

## Who sees what

- A member: their own places only. Another member's
  place: 404, recorded as a refused AuditEvent.
- The attendee list (display name, email, phone, time
  of registration; counts of cancellations and late
  ones): the event's current organizers and the
  administrator. Members are told at registration.
- No public attendee list; contacts on no other page.

## Not here

- Two requests at the same moment: Chapter 33.
- Emails to members: Chapters 43-44.
- Waitlist and check-in: Chapter 46.
- Registration questions: Chapter 38; download: 41.

Each row of the reasons table becomes a test in Step 5, and the “Who sees what” list becomes the matrix in Step 11. The note says what is not decided here and where it will be, so a reader of the design is not left guessing.

Step 3: Registration times, a constraint code, and a phone number

Tests first. Add at the end of events/tests.py:

class RegistrationWindowTests(TestCase):
    """The registration times and their database rules."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = editor()
        cls.event = future_draft(cls.sam)

    def test_the_order_holds_in_the_database(self):
        rows = Event.objects.filter(pk=self.event.pk)
        start = self.event.starts_at
        hour = timedelta(hours=1)
        for changes in (
            {'registration_closes_at': start + hour},
            {'cancellation_deadline': start + hour},
            {'registration_opens_at': start,
             'registration_closes_at': start - hour},
        ):
            with self.subTest(changes=changes):
                with self.assertRaises(IntegrityError):
                    with transaction.atomic():
                        rows.update(**changes)

    def test_blank_times_pass_the_rules(self):
        Event.objects.filter(pk=self.event.pk).update(
            registration_opens_at=None,
            registration_closes_at=None,
            cancellation_deadline=None,
        )
        self.event.refresh_from_db()
        self.event.full_clean()

The first test writes each wrong order straight to the database with update(), which skips every Python check, so only a database rule can refuse it. The second shows that blank times pass the same rules: a draft may leave them empty.

uv run python manage.py test events -k RegistrationWindow
Found 2 test(s).
Creating test database for alias 'default'...
...
KeyError: 'registration_opens_at'
KeyError: 'registration_closes_at'
KeyError: 'cancellation_deadline'
Ran 2 tests in ...s

FAILED (errors=4)
Destroying test database for alias 'default'...

In events/models.py, add three times and the phone setting to Event, after the status field:

    registration_opens_at = models.DateTimeField(
        'registration opens', null=True, blank=True,
        help_text='Blank: when the event is published.',
    )
    registration_closes_at = models.DateTimeField(
        'registration closes', null=True, blank=True,
        help_text='Needed to publish; by the start.',
    )
    cancellation_deadline = models.DateTimeField(
        null=True, blank=True,
        help_text='Needed to publish; by the start. Later '
                  'cancellations count as late.',
    )
    phone_required = models.BooleanField(
        'ask for a phone number', default=False,
    )

All three times allow NULL, because a draft may not have them yet; Step 4 makes the closing time and the deadline required to publish. help_text appears on the event form and in the admin. Then add three rules at the end of Meta.constraints, after event_status_valid:

            models.CheckConstraint(
                condition=(
                    models.Q(registration_opens_at=None)
                    | models.Q(registration_closes_at=None)
                    | models.Q(registration_opens_at__lt=(
                        models.F('registration_closes_at')
                    ))
                ),
                name='event_opens_before_closes',
                violation_error_message=(
                    'Registration must open before it '
                    'closes.'
                ),
            ),
            models.CheckConstraint(
                condition=(
                    models.Q(registration_closes_at=None)
                    | models.Q(registration_closes_at__lte=(
                        models.F('starts_at')
                    ))
                ),
                name='event_closes_by_start',
                violation_error_message=(
                    'Registration must close by the start.'
                ),
            ),
            models.CheckConstraint(
                condition=(
                    models.Q(cancellation_deadline=None)
                    | models.Q(cancellation_deadline__lte=(
                        models.F('starts_at')
                    ))
                ),
                name='event_deadline_by_start',
                violation_error_message=(
                    'The cancellation deadline must be by '
                    'the start.'
                ),
            ),

Each rule has a branch for a blank value, as Chapter 22’s rules did: Q(registration_closes_at=None) means “is NULL”, so an empty time passes. Without the branch the rule would still pass, because a comparison with NULL is unknown and a CHECK refuses only false, but the intent would be hidden. Make the migration:

uv run python manage.py makemigrations events --name registration
Migrations for 'events':
  events/migrations/0006_registration.py
    + Add field cancellation_deadline to event
    + Add field phone_required to event
    + Add field registration_closes_at to event
    + Add field registration_opens_at to event
    + Create constraint event_opens_before_closes on model
    event
    + Create constraint event_closes_by_start on model event
    + Create constraint event_deadline_by_start on model
    event

To see what SQLite is asked to do, print the SQL with uv run python manage.py sqlmigrate events 0006. The output is long, because SQLite cannot add a CHECK rule to an existing table: Django builds a new table with every rule, copies the rows across, and renames it. One rule in it reads:

... CONSTRAINT "event_closes_by_start" CHECK
  (("registration_closes_at" IS NULL OR
    "registration_closes_at" <= ("starts_at"))) ...

Events that are already published have no closing time and no deadline, and from Step 4 a published event is expected to have both. Fill them with a data migration, a migration that changes rows rather than tables, as Chapter 30 did for groups:

The command is split; in PowerShell the backtick continues it, with no space after it:

uv run python manage.py makemigrations events `
  --empty --name fill_window

In Git Bash, macOS, Linux, or WSL, the backslash does the same:

uv run python manage.py makemigrations events \
  --empty --name fill_window
Migrations for 'events':
  events/migrations/0007_fill_window.py

Keep the generated first line, and replace the rest of events/migrations/0007_fill_window.py with:

from django.db import migrations
from django.db.models import F


def fill_window(apps, schema_editor):
    """Close registration at the start of older events.

    Drafts are left blank: publishing asks for both times.
    """
    Event = apps.get_model('events', 'Event')
    Event.objects.exclude(status='draft').filter(
        registration_closes_at=None,
    ).update(registration_closes_at=F('starts_at'))
    Event.objects.exclude(status='draft').filter(
        cancellation_deadline=None,
    ).update(cancellation_deadline=F('starts_at'))


class Migration(migrations.Migration):

    dependencies = [
        ('events', '0006_registration'),
    ]

    operations = [
        migrations.RunPython(
            fill_window, migrations.RunPython.noop
        ),
    ]

For published and cancelled events, registration closes and cancellation becomes late at the start, which is what was true before this chapter: nobody could register after an event began. F('starts_at') copies each event’s own start inside the database, in one UPDATE. Drafts keep blank times, and publishing will ask for them. The reverse is noop, because removing the columns on the way back removes the values too. Apply both migrations and look at the result:

uv run python manage.py migrate
Operations to perform:
  Apply all migrations: account, accounts, admin, audit,
    auth, contenttypes, events, mfa, registrations, sessions,
    socialaccount
Running migrations:
  Applying events.0006_registration... OK
  Applying events.0007_fill_window... OK

To look, save this practice file as s_look.py beside manage.py, run it with uv run python manage.py shell -c "exec(open('s_look.py').read())", and delete it:

"""Practice: which events have a closing time now."""
from events.models import Event

for event in Event.objects.all():
    filled = event.registration_closes_at == event.starts_at
    print(event.status, filled)

Your list shows your own events; in the chapter’s copy there was one published event and one draft:

published True
published True
draft False
published True
published True
draft False
draft False
uv run python manage.py test events -k RegistrationWindow
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s

OK
Destroying test database for alias 'default'...

Next, give Chapter 21’s unique rule a code. In registrations/models.py, add one line to the registration_one_active constraint, after its name:

                name='registration_one_active',
                violation_error_code='already_registered',

A conditional unique rule has no code unless you give one, so a form or test that needs to recognize it would have to match its message. With a code, Step 6’s test can ask for already_registered. The migration records the change with an AlterConstraint operation, which leaves the table alone, because the code lives only in Python:

The command is split; in PowerShell the backtick continues it, with no space after it:

uv run python manage.py makemigrations registrations `
  --name constraint_code

In Git Bash, macOS, Linux, or WSL, the backslash does the same:

uv run python manage.py makemigrations registrations \
  --name constraint_code
Migrations for 'registrations':
  registrations/migrations/0003_constraint_code.py
    ~ Alter constraint registration_one_active on
    registration

Now the phone number. Add the package at the exact version checked for this chapter, together with phonenumbers, the library it uses, also pinned:

# PowerShell
uv add "django-phonenumber-field[phonenumbers]==9.0.0" `
  "phonenumbers==9.0.44"
# macOS/Linux/WSL and Git Bash
uv add "django-phonenumber-field[phonenumbers]==9.0.0" \
  "phonenumbers==9.0.44"
Resolved 23 packages in 16ms
Installed 2 packages in 1.01s
 + django-phonenumber-field==9.0.0
 + phonenumbers==9.0.44

In config/settings.py, add the app at the end of INSTALLED_APPS, after 'allauth.mfa',:

    'phonenumber_field',

and add at the end of the file:

# Phone numbers (Chapter 31): a number typed without a
# country code is read as an Indian number.
PHONENUMBER_DEFAULT_REGION = 'IN'

In accounts/models.py, import the model field after the django.utils import:

from phonenumber_field.modelfields import PhoneNumberField

and add the field to Profile, after timezone:

    phone = PhoneNumberField(
        blank=True,
        help_text='Shown only to the organizers of events '
                  'you register for.',
    )

blank=True makes the number optional; an empty value is stored as an empty string, as Django does for text. Make the migration and apply everything:

The command is split; in PowerShell the backtick continues it, with no space after it:

uv run python manage.py makemigrations accounts `
  --name profile_phone

In Git Bash, macOS, Linux, or WSL, the backslash does the same:

uv run python manage.py makemigrations accounts \
  --name profile_phone
Migrations for 'accounts':
  accounts/migrations/0005_profile_phone.py
    + Add field phone to profile
uv run python manage.py migrate
Operations to perform:
  Apply all migrations: account, accounts, admin, audit,
    auth, contenttypes, events, mfa, registrations, sessions,
    socialaccount
Running migrations:
  Applying accounts.0005_profile_phone... OK
  Applying registrations.0003_constraint_code... OK

Step 4: The event form, publishing, copies, and the profile

Three earlier helpers need the new times. In events/tests.py, replace future_draft(), which makes a complete draft, with:

def future_draft(organizer=None, **changes):
    """Create a complete draft that starts next week.

    Registration and cancellation close at the start.
    """
    fields = {
        'status': Event.Status.DRAFT,
        'starts_at': timezone.now() + timedelta(days=7),
        'description': 'Bring a laptop and a question.',
    } | changes
    fields.setdefault('registration_closes_at',
                      fields['starts_at'])
    fields.setdefault('cancellation_deadline',
                      fields['starts_at'])
    event = save_event(**fields)
    if organizer:
        event.add_organizer(organizer)
    return event

A complete draft now has a closing time and a deadline, at its start unless a test says otherwise. Replace as_sent(), which builds what the edit page sends, with:

def as_sent(event, **changes):
    """Return what the edit page sends, before any change."""
    form = EventForm(instance=event)
    data = {}
    for name in form.fields:
        value = form[name].value()
        if isinstance(value, datetime):
            value = f'{value:%Y-%m-%dT%H:%M}'
        # A blank time is sent as an empty box.
        data[name] = '' if value is None else value
    return data | changes

The test client refuses None as a form value, and an empty time box sends an empty string. Now the new tests. Add at the end of events/tests.py:

class WindowFormTests(TestCase):
    """Readiness, copies, and the form learn the window."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = editor()
        cls.event = future_draft(cls.sam)

    def test_publishing_needs_both_times(self):
        event = future_draft(
            self.sam, registration_closes_at=None,
            cancellation_deadline=None,
        )
        self.assertEqual(event.readiness_problems(), [
            'Set when registration closes.',
            'Set a cancellation deadline.',
        ])

    def test_a_copy_moves_the_window(self):
        week = timedelta(days=7)
        self.event.registration_opens_at = (
            self.event.starts_at - week
        )
        self.event.save()
        copy = self.event.copy_as_draft(
            self.sam, self.event.starts_at + week
        )
        for name in ('registration_opens_at',
                     'registration_closes_at',
                     'cancellation_deadline'):
            with self.subTest(name=name):
                self.assertEqual(
                    getattr(copy, name),
                    getattr(self.event, name) + week,
                )

    def test_the_form_reads_times_in_the_event_zone(self):
        form = new_event_form(
            registration_closes_at='2026-12-03T12:00',
            cancellation_deadline='2026-12-02T18:00',
            phone_required='on',
        )
        self.assertTrue(form.is_valid(), form.errors)
        event = form.save()
        self.assertEqual(
            event.registration_closes_at,
            datetime(2026, 12, 3, 17, 0, tzinfo=UTC),
        )
        self.assertIsNone(event.registration_opens_at)
        self.assertTrue(event.phone_required)

    def test_the_form_refuses_a_late_closing(self):
        form = new_event_form(
            registration_closes_at='2026-12-03T20:00'
        )
        self.assertFalse(form.is_valid())
        self.assertEqual(form.non_field_errors(),
                         ['Registration must close by the '
                          'start.'])

and at the end of accounts/tests.py:

class ProfilePhoneTests(TestCase):
    """A phone number on the profile, checked and kept."""

    url = '/accounts/profile/'

    @classmethod
    def setUpTestData(cls):
        cls.sai = User.objects.create_user(
            'sai@example.org', PASSWORD, display_name='Sai'
        )

    def setUp(self):
        self.client.force_login(self.sai)

    def save(self, phone):
        """Send the profile form with this phone number."""
        return self.client.post(self.url, {
            'display_name': 'Sai', 'timezone': '',
            'phone': phone,
        })

    def test_a_national_number_is_kept_in_full(self):
        self.save('098765 43210')
        self.assertEqual(Profile.of(self.sai).phone,
                         '+919876543210')
        page = self.client.get(self.url)
        self.assertContains(page, 'type="tel"')

    def test_another_country_needs_its_code(self):
        self.save('+44 113 496 0000')
        self.assertEqual(Profile.of(self.sai).phone.as_e164,
                         '+441134960000')

    def test_a_wrong_number_is_refused(self):
        response = self.save('12345')
        self.assertContains(response, 'Enter a valid phone')
        self.assertEqual(Profile.of(self.sai).phone, '')

    def test_the_number_may_stay_blank(self):
        response = self.save('')
        self.assertEqual(response.status_code, 302)
uv run python manage.py test -k WindowForm -k ProfilePhone
Found 8 test(s).
Creating test database for alias 'default'...
...
AttributeError: 'str' object has no attribute 'as_e164'
AssertionError: '' != '+919876543210'
AssertionError: 302 != 200 : Couldn't retrieve content:
    Response code was 302 (expected 200)
Ran 8 tests in ...s

FAILED (failures=8, errors=1)
Destroying test database for alias 'default'...

The event form reads typed times in the event’s own zone (Chapter 24), and the new times must be read the same way. In events/forms.py, add a list of every time the form reads, after BOX_FORMAT:

# Every time the event form reads in the event's zone.
TIMES = ['starts_at', 'ends_at', 'registration_opens_at',
         'registration_closes_at', 'cancellation_deadline']

Replace EventForm’s Meta from fields to the end of widgets with:

        fields = ['title', 'description', 'timezone',
                  'starts_at', 'ends_at', 'location',
                  'capacity', 'registration_opens_at',
                  'registration_closes_at',
                  'cancellation_deadline', 'phone_required']
        labels = {'starts_at': 'Starts', 'ends_at': 'Ends'}
        help_texts = {
            'description': 'Needed before the event can be '
                           'published.',
            'location': 'A venue address, or Online.',
        }
        widgets = {
            'description': forms.Textarea(attrs={'rows': 5}),
        } | {name: local_input() for name in TIMES}

The | joins two dictionaries: the description’s box, and a date-and-time box for every name in TIMES. Replace show_saved_times(), which fills the boxes on the edit page:

    def show_saved_times(self):
        """Show stored times as typed in the event's zone."""
        zone = ZoneInfo(self.saved_zone)
        for name in TIMES:
            moment = getattr(self.instance, name)
            if moment is None:
                continue
            local = moment.astimezone(zone)
            local = local.replace(tzinfo=None)
            self.initial[name] = local
            self.shown[name] = local.strftime(BOX_FORMAT)
            self.fields[name].help_text = (
                'Saved: ' + reading(moment, self.saved_zone)
            )

A blank time is skipped. In clean(), change the loop that reads the times to use the list:

        zone = data.get('timezone')
        for name in TIMES:
            if zone and data.get(name):
                try:
                    data[name] = self.read_time(
                        name, data[name], zone
                    )
                except ValidationError as error:
                    self.add_error(name, error)

And in read_time(), which keeps a time the member did not touch, use .get(), because a time that was blank has nothing saved to compare with:

    def read_time(self, name, value, zone):
        """Keep a time left alone; read others in zone."""
        typed = timezone.make_naive(value)
        unchanged = (zone == self.saved_zone and
                     typed.strftime(BOX_FORMAT)
                     == self.shown.get(name))
        if unchanged:
            return getattr(self.instance, name)
        return in_zone(value, zone)

The order rules need no code in the form. A ModelForm runs the model’s constraints through full_clean(), so “Registration must close by the start.” appears at the top of the form, as test_the_form_refuses_a_late_closing expects.

In events/models.py, add a small helper after the line REFUSED = AuditEvent.Outcome.REFUSED:

def moved(moment, by):
    """Return moment moved by a timedelta; None stays."""
    return None if moment is None else moment + by

In readiness_problems(), add two checks after the organizer check, before return problems:

        if self.registration_closes_at is None:
            problems.append('Set when registration closes.')
        if self.cancellation_deadline is None:
            problems.append('Set a cancellation deadline.')

and replace copy_as_draft():

    def copy_as_draft(self, member, starts_at):
        """Return a new draft with this event's details.

        It starts at starts_at, organized by member; its
        registration times move with the start.
        """
        shift = starts_at - self.starts_at
        with transaction.atomic():
            copy = Event.objects.create(
                title=self.title,
                description=self.description,
                timezone=self.timezone,
                location=self.location,
                capacity=self.capacity,
                phone_required=self.phone_required,
                starts_at=starts_at,
                ends_at=self.ends_at + shift,
                registration_opens_at=moved(
                    self.registration_opens_at, shift),
                registration_closes_at=moved(
                    self.registration_closes_at, shift),
                cancellation_deadline=moved(
                    self.cancellation_deadline, shift),
            )
            copy.add_organizer(member)
        return copy

A copy keeps every time in the same place relative to its start: a clinic that closed registration a day before still does. ends_at + shift replaces Chapter 26’s length sum and means the same.

The admin shows the new fields too. In events/admin.py, replace EventAdmin.fields:

    fields = ['title', 'description', 'status',
              'starts_at', 'ends_at',
              'timezone', 'local_start', 'location',
              'capacity', 'registration_opens_at',
              'registration_closes_at',
              'cancellation_deadline', 'phone_required']

and get_form(), so each time says it is in UTC, as the start and end already do:

    def get_form(self, request, obj=None, **kwargs):
        """Say on the form that its times are in UTC."""
        kwargs['help_texts'] = dict.fromkeys(
            ['starts_at', 'ends_at', 'registration_opens_at',
             'registration_closes_at',
             'cancellation_deadline'], UTC_HELP,
        )
        return super().get_form(request, obj, **kwargs)

Then the profile. In accounts/forms.py, import the form field after from django import forms:

from phonenumber_field.formfields import PhoneNumberField

add the help text after NAME_HELP:

PHONE_HELP = ('Shown only to the organizers of events you '
              'register for. Without +, read as an Indian '
              'number.')

and replace ProfileForm:

class ProfileForm(forms.Form):
    """The signed-in member's name, zone, and phone."""

    display_name = forms.CharField(
        max_length=100, help_text=NAME_HELP,
    )
    timezone = forms.ChoiceField(
        choices=ZONE_CHOICES, required=False,
        label='Time zone (optional)',
    )
    phone = PhoneNumberField(
        required=False, label='Phone number (optional)',
        help_text=PHONE_HELP,
    )

    def save(self, user):
        """Save the name to the user, the rest to Profile."""
        user.display_name = self.cleaned_data['display_name']
        user.save(update_fields=['display_name'])
        profile = Profile.of(user)
        profile.timezone = self.cleaned_data['timezone']
        profile.phone = self.cleaned_data['phone']
        profile.full_clean()
        profile.save()

In accounts/views.py, give the form the saved number, replacing the form = ProfileForm(initial=...) lines under else::

        profile = Profile.of(user)
        form = ProfileForm(initial={
            'display_name': user.display_name,
            'timezone': profile.timezone,
            'phone': profile.phone,
        })

The form field reads “098765 43210” as an Indian number, refuses “12345”, and renders a box of type tel, which phones answer with a number keypad. Update the design note for event states. In docs/design/event-states.md, replace the publish item with:

- publish: draft to published. Refused when it is not a
  draft, has no description, does not start in the future,
  has no current organizer, or has no registration closing
  time or cancellation deadline (Chapter 31).

and the copy lines under “Request path” with:

  event's zone; event.copy_as_draft(user, starts_at) copies
  title, description, place, time zone, capacity, length,
  the phone setting, and the registration times, moved
  with the start; never registrations, status, or other
  organizers; 302 to the new draft's edit page.
uv run python manage.py test -k WindowForm -k ProfilePhone
Found 8 test(s).
Creating test database for alias 'default'...
...
Ran 8 tests in ...s

OK
Destroying test database for alias 'default'...

Now run the two apps whose pages changed. Three earlier tests count fields, and the forms have more of them:

uv run python manage.py test events config
Found 197 test(s).
Creating test database for alias 'default'...
...
Ran 197 tests in ...s

FAILED (failures=3)
Destroying test database for alias 'default'...

Each failure is a count, not a fault, so update each to the new number. In events/tests.py, in FormMarkupTests, the event form now has eleven fields, eight of them plain boxes:

        for text, count in (('class="fieldset"', 11),
                            ('class="input w-full"', 8),

In EditMarkupTests.test_tick_box_is_styled_and_linked, the edit page has two tick boxes now, the zone confirmation and the phone setting, so the checkbox class is counted on its own:

        # Two tick boxes: the new zone and the phone setting.
        self.assertContains(response, 'class="checkbox"',
                            count=2)
        for text in ('for="id_confirm_zone"',
                     'aria-invalid="true"', described):
            self.assertContains(response, text, count=1)

And in config/tests.py, in test_event_times_keep_their_shortcuts, the admin’s event page has five times with date and time shortcuts, not two:

                response, f'class="input w-full {name}"',
                count=5,
uv run python manage.py test
Found 298 test(s).
Creating test database for alias 'default'...
...
Ran 298 tests in ...s

OK
Destroying test database for alias 'default'...

Try the form: open New event, and the three times appear after Capacity, with a box for “Ask for a phone number”. Leave the closing time empty, save, and press Publish: “Set when registration closes.” and “Set a cancellation deadline.” appear, and the event stays a draft.

Common Error: “Cannot encode None for key ... as POST data”

A test that builds form data from saved values, as as_sent() does, sends None for a blank time, and the test client refuses it with a TypeError before any request is made. Send an empty string, which is what a browser sends for an empty box.

Step 5: The rules as named reasons

Tests first, one for each reason and each edge. Replace the imports at the top of registrations/tests.py, down to User = get_user_model(), with the imports this chapter’s tests need:

"""Tests for the registrations app."""
from datetime import UTC, datetime, timedelta
from unittest import mock

from allauth.account.models import EmailAddress
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.db import IntegrityError, connection, transaction
from django.db.models import ProtectedError
from django.test import TestCase
from django.test.utils import CaptureQueriesContext
from django.urls import reverse
from django.utils import timezone

from accounts.models import Profile
from audit.models import AuditEvent
from events.models import ORGANIZERS, Event
from events.tests import SAI_PASSWORD as PASSWORD
from events.tests import admin_url, in_group, outcome
from .models import Registration

and add at the end of the file:

START = datetime(2027, 3, 4, 13, 30, tzinfo=UTC)
TICK = timedelta(microseconds=1)


def verified(email):
    """Create a member whose email address is confirmed."""
    name = email.split('@')[0].title()
    user = User.objects.create_user(email, display_name=name)
    EmailAddress.objects.create(user=user, email=email,
                                verified=True, primary=True)
    return user


def clinic(**changes):
    """Create Sam's published clinic, open for two places.

    Registration closes a day before the start; a cancel
    is late from two days before.
    """
    fields = {
        'title': 'Django clinic',
        'starts_at': START,
        'ends_at': START + timedelta(hours=2),
        'timezone': 'Asia/Kolkata',
        'location': 'Online',
        'capacity': 2,
        'status': Event.Status.PUBLISHED,
        'registration_opens_at': START - timedelta(days=14),
        'registration_closes_at': START - timedelta(days=1),
        'cancellation_deadline': START - timedelta(days=2),
    }
    return Event.objects.create(**(fields | changes))


class RegistrationRuleTests(TestCase):
    """Each reason a member cannot register, by code."""

    @classmethod
    def setUpTestData(cls):
        cls.event = clinic()
        cls.sai = verified('sai@example.org')
        cls.now = START - timedelta(days=5)

    def problems(self, member=None, now=None):
        """Ask the event why member cannot register."""
        return self.event.registration_problems(
            member or self.sai, now or self.now
        )

    def test_an_open_event_has_no_problems(self):
        self.assertEqual(self.problems(), [])

    def test_opening_is_inclusive(self):
        opens = self.event.registration_opens_at
        self.assertEqual(self.problems(now=opens - TICK),
                         ['not_open'])
        self.assertEqual(self.problems(now=opens), [])

    def test_closing_is_exclusive(self):
        closes = self.event.registration_closes_at
        self.assertEqual(self.problems(now=closes - TICK), [])
        self.assertEqual(self.problems(now=closes),
                         ['closed'])

    def test_a_blank_opening_means_open_now(self):
        self.event.registration_opens_at = None
        self.assertEqual(self.problems(), [])

    def test_only_published_events_take_places(self):
        for status in ('draft', 'cancelled'):
            with self.subTest(status=status):
                self.event.status = status
                self.assertEqual(self.problems(),
                                 ['not_published'])

    def test_a_past_event_is_closed(self):
        later = START + timedelta(days=1)
        self.assertEqual(self.problems(now=later),
                         ['closed'])

    def test_a_full_event_says_so(self):
        for email in ('raj@example.org', 'soni@example.org'):
            self.event.registrations.create(
                member=verified(email)
            )
        self.assertEqual(self.problems(), ['full'])

    def test_a_place_already_held_is_named(self):
        self.event.registrations.create(member=self.sai)
        self.assertEqual(self.problems(),
                         ['already_registered'])

    def test_an_unconfirmed_email_is_named(self):
        soni = User.objects.create_user(
            'soni@example.org', display_name='Soni'
        )
        self.assertEqual(self.problems(soni), ['unverified'])

    def test_a_missing_phone_is_named(self):
        self.event.phone_required = True
        self.assertEqual(self.problems(), ['phone_missing'])
        Profile.objects.create(user=self.sai,
                               phone='+919876543210')
        self.sai.refresh_from_db()
        self.assertEqual(self.problems(), [])

    def test_reasons_add_up(self):
        soni = User.objects.create_user(
            'soni@example.org', display_name='Soni'
        )
        closes = self.event.registration_closes_at
        self.assertEqual(self.problems(soni, closes),
                         ['closed', 'unverified'])

TICK is one microsecond, the smallest step a Django time field stores, so closes - TICK is the last instant at which registration is open. clinic() fixes every time, so the tests give the same answer on any day.

uv run python manage.py test registrations -k Rule
Found 11 test(s).
Creating test database for alias 'default'...
...
AttributeError: 'Event' object has no attribute
    'registration_problems'
Ran 11 tests in ...s

FAILED (errors=12)
Destroying test database for alias 'default'...

In events/models.py, import allauth’s check for a confirmed address before from django.conf import settings:

from allauth.account.utils import has_verified_email

and change the django.db import, which Step 6 needs:

from django.db import IntegrityError, models, transaction

Add the reasons after the line REFUSED = AuditEvent.Outcome.REFUSED:

# Why a member cannot register, by code (Chapter 31).
REASONS = {
    'not_published': 'This event is not open for '
                     'registration.',
    'not_open': 'Registration has not opened yet.',
    'closed': 'Registration has closed.',
    'full': 'This event is full.',
    'already_registered': 'You already have a place.',
    'unverified': 'Confirm your email address to '
                  'register.',
    'phone_missing': 'This event asks for your phone '
                     'number.',
}


def refusal(codes):
    """Return one ValidationError naming every reason."""
    return ValidationError([
        ValidationError(REASONS[code], code=code)
        for code in codes
    ])


def phone_of(member):
    """Return member's phone number, or '' if none."""
    # A member made outside sign-up may have no Profile.
    profile = getattr(member, 'profile', None)
    return profile.phone if profile else ''

REASONS keeps every message in one place, keyed by its code. refusal() turns a list of codes into one ValidationError that holds an error per reason, each with its code, the shape Django’s forms and messages already understand. phone_of() returns an empty string when a member has no Profile row yet, which happens for members made in the shell or by createsuperuser.

Then add three methods to Event, after places_taken():

    def place_of(self, member):
        """Return member's active place here, or None."""
        return self.registrations.active().filter(
            member=member
        ).first()

    def open_problems(self, now):
        """List, by code, what stops anyone registering.

        Opening is inclusive and closing exclusive: at the
        closing instant, registration has closed.
        """
        if self.status != self.Status.PUBLISHED:
            return ['not_published']
        problems = []
        opens = self.registration_opens_at
        if opens is not None and now < opens:
            problems.append('not_open')
        # Publishing needs a closing time; a row saved
        # without one closes at the start.
        closes = self.registration_closes_at or self.starts_at
        if now >= closes:
            problems.append('closed')
        if self.places_taken() >= self.capacity:
            problems.append('full')
        return problems

    def registration_problems(self, member, now):
        """List, by code, why member cannot register now.

        An empty list means member may register.
        """
        if self.place_of(member):
            return ['already_registered']
        problems = self.open_problems(now)
        if not has_verified_email(member, member.email):
            problems.append('unverified')
        if self.phone_required and not phone_of(member):
            problems.append('phone_missing')
        return problems

open_problems() holds the reasons that apply to everyone, so the event page can use it for visitors in Step 8. registration_problems() adds the member’s own: a place already held, an email address not confirmed, and a phone number missing. has_verified_email(member, member.email) asks allauth whether the account’s own address is confirmed; another confirmed address on the account does not count, because Sam’s list shows member.email.

uv run python manage.py test registrations -k Rule
Found 11 test(s).
Creating test database for alias 'default'...
...
Ran 11 tests in ...s

OK
Destroying test database for alias 'default'...

Common Error: a boundary test that passes in the morning

A test that sets the closing time to timezone.now() + timedelta(hours=1) and checks that registration is open passes until someone runs the suite within an hour of a slow step, or on a machine whose clock is set oddly, and then fails without any code change. Tests at a boundary pass the instant they mean, as these do. The interview’s L4 shows the failure.

Step 6: register(), in a transaction

Tests first. Add at the end of registrations/tests.py:

class RegisterTests(TestCase):
    """Event.register(): a place, or a named refusal."""

    @classmethod
    def setUpTestData(cls):
        cls.event = clinic()
        cls.sai = verified('sai@example.org')
        cls.now = START - timedelta(days=5)

    def test_a_place_is_made(self):
        place = self.event.register(self.sai, self.now)
        self.assertEqual(place.status, 'active')
        self.assertEqual(place.registered_at, self.now)
        self.assertEqual(self.event.places_taken(), 1)

    def test_a_refusal_names_why_and_saves_nothing(self):
        closes = self.event.registration_closes_at
        with self.assertRaises(ValidationError) as caught:
            self.event.register(self.sai, closes)
        self.assertEqual(caught.exception.messages,
                         ['Registration has closed.'])
        self.assertEqual(caught.exception.error_list[0].code,
                         'closed')
        self.assertFalse(Registration.objects.exists())

    def test_a_second_request_keeps_one_place(self):
        self.event.register(self.sai, self.now)
        with self.assertRaises(ValidationError) as caught:
            self.event.register(self.sai, self.now)
        self.assertEqual(caught.exception.error_list[0].code,
                         'already_registered')
        self.assertEqual(self.event.places_taken(), 1)

    def test_the_constraint_catches_a_missed_check(self):
        # A place appears after the checks ran.
        self.event.registrations.create(member=self.sai)
        with mock.patch.object(Event, 'registration_problems',
                               return_value=[]):
            with self.assertRaises(ValidationError) as caught:
                self.event.register(self.sai, self.now)
        self.assertEqual(caught.exception.error_list[0].code,
                         'already_registered')
        self.assertEqual(self.event.places_taken(), 1)

    def test_another_database_error_is_not_hidden(self):
        broken = IntegrityError('NOT NULL constraint failed')
        with mock.patch.object(Registration, 'save',
                               side_effect=broken):
            with self.assertRaises(IntegrityError):
                self.event.register(self.sai, self.now)

    def test_the_constraint_has_a_code(self):
        self.event.registrations.create(member=self.sai)
        again = Registration(event=self.event, member=self.sai)
        with self.assertRaises(ValidationError) as caught:
            again.full_clean()
        errors = caught.exception.error_dict['__all__']
        self.assertEqual(errors[0].code, 'already_registered')

Two tests stand in for events that cannot be staged by hand. mock.patch.object() replaces a method for the length of a with block. In test_the_constraint_catches_a_missed_check, registration_problems() is told to find nothing although Sai holds a place, as if a second request had inserted her place between the check and the insert; only the database rule is left to refuse it. In test_another_database_error_is_not_hidden, saving fails with a different IntegrityError, which must reach the caller.

uv run python manage.py test registrations -k RegisterTests
Found 6 test(s).
Creating test database for alias 'default'...
...
AttributeError: 'Event' object has no attribute 'register'
Ran 6 tests in ...s

FAILED (errors=5)
Destroying test database for alias 'default'...

Add register() to Event, after registration_problems():

    def register(self, member, now):
        """Give member a place, or raise ValidationError.

        The unique rule is the backstop for a place made
        between the check and the insert. Chapter 33 locks
        the event before counting.
        """
        with transaction.atomic():
            problems = self.registration_problems(member, now)
            if problems:
                raise refusal(problems)
            try:
                with transaction.atomic():
                    return self.registrations.create(
                        member=member, registered_at=now
                    )
            except IntegrityError:
                # Only the one-active-place rule means a
                # repeat; any other failure is re-raised.
                if self.place_of(member) is None:
                    raise
            raise refusal(['already_registered'])

The outer atomic() holds the check and the insert together; Chapter 33 adds its lock at the top of it. The inner atomic() wraps only the insert, so a refused insert rolls back to its savepoint and the outer block can still ask the database a question. The question is place_of(member): a place found means the request was a repeat, and the member hears “You already have a place”; nothing found means another rule failed, and the error is raised again unchanged.

uv run python manage.py test registrations -k RegisterTests
Found 6 test(s).
Creating test database for alias 'default'...
...
Ran 6 tests in ...s

OK
Destroying test database for alias 'default'...

Common Error: every IntegrityError reported as “already registered”

An except IntegrityError: that always answers “You already have a place” hides real faults: a value the database refuses, a missing table after a bad deployment. The member sees a friendly message, the place does not exist, and nobody is told. Translate only the error you expect, and check that it is the one you expect, as register() does.

Common Error: TransactionManagementError after catching an IntegrityError

Put the try around self.registrations.create() directly inside the outer atomic(), without the inner block, and the next query, place_of(member), fails with “An error occurred in the current transaction. You can’t execute queries until the end of the ’atomic’ block.” The insert’s failure broke the outer block. Wrap the statement that may fail in its own atomic(), and catch outside it.

Step 7: cancel(), once, and late

Tests first. Add at the end of registrations/tests.py:

class CancelTests(TestCase):
    """Registration.cancel(): a place released once."""

    @classmethod
    def setUpTestData(cls):
        cls.event = clinic()
        cls.raj = verified('raj@example.org')

    def setUp(self):
        self.place = self.event.register(
            self.raj, START - timedelta(days=5)
        )

    def test_cancel_releases_the_place_once(self):
        when = START - timedelta(days=3)
        self.assertTrue(self.place.cancel(when))
        self.assertEqual(self.place.status, 'cancelled')
        self.assertEqual(self.place.cancelled_at, when)
        self.assertEqual(self.event.places_taken(), 0)
        later = START - timedelta(days=2, hours=1)
        self.assertFalse(self.place.cancel(later))
        self.place.refresh_from_db()
        self.assertEqual(self.place.cancelled_at, when)

    def test_a_stale_copy_changes_nothing(self):
        other = Registration.objects.get(pk=self.place.pk)
        self.place.cancel(START - timedelta(days=3))
        self.assertFalse(other.cancel(START - TICK))
        self.assertEqual(
            Registration.objects.filter(
                status='cancelled').count(), 1,
        )

    def test_late_from_the_deadline(self):
        deadline = self.event.cancellation_deadline
        self.place.cancel(deadline - TICK)
        self.assertFalse(self.place.is_late())
        again = self.event.register(self.raj, deadline - TICK)
        again.cancel(deadline)
        self.assertTrue(again.is_late())

    def test_no_cancel_once_the_event_starts(self):
        with self.assertRaises(ValidationError) as caught:
            self.place.cancel(START)
        self.assertEqual(caught.exception.code, 'started')
        self.assertTrue(self.place.cancel(START - TICK))

    def test_a_member_may_register_again(self):
        self.place.cancel(START - timedelta(days=4))
        again = self.event.register(
            self.raj, START - timedelta(days=4)
        )
        self.assertNotEqual(again.pk, self.place.pk)
        self.assertEqual(self.event.places_taken(), 1)

    def test_a_cancelled_event_keeps_places(self):
        self.event.cancel()
        self.place.refresh_from_db()
        self.assertEqual(self.place.status, 'active')
        self.assertTrue(
            self.place.cancel(START - timedelta(days=3))
        )

    def test_counts_for_the_organizer(self):
        deadline = self.event.cancellation_deadline
        self.place.cancel(deadline - TICK)
        again = self.event.register(self.raj, deadline - TICK)
        again.cancel(deadline + TICK)
        self.assertEqual(
            self.event.registrations.cancellation_counts(),
            {'cancelled': 2, 'late': 1},
        )

test_a_stale_copy_changes_nothing loads the same place twice, as two requests would, cancels one copy, and asks the other to cancel too. The second must change nothing, even though its own copy still says “active”.

uv run python manage.py test registrations -k CancelTests
Found 7 test(s).
Creating test database for alias 'default'...
...
AttributeError: 'Registration' object has no attribute
    'cancel'
Ran 7 tests in ...s

FAILED (errors=7)
Destroying test database for alias 'default'...

In registrations/models.py, import ValidationError after from django.conf import settings:

from django.core.exceptions import ValidationError

Add a count for organizers to RegistrationQuerySet, after active():

    def cancellation_counts(self):
        """Count cancelled places, and how many were late."""
        cancelled = models.Q(status='cancelled')
        late = cancelled & models.Q(
            cancelled_at__gte=models.F(
                'event__cancellation_deadline'
            )
        )
        return self.aggregate(
            cancelled=models.Count('pk', filter=cancelled),
            late=models.Count('pk', filter=late),
        )

F('event__cancellation_deadline') compares each row with its own event’s deadline inside the database, and Count(..., filter=...) counts only matching rows; aggregate() returns both numbers from one query. Then add two methods at the end of Registration, after __str__():

    def cancel(self, now):
        """Release this place at now; return True if it did.

        A place already cancelled stays as it is, so a
        repeated request changes nothing.
        """
        if now >= self.event.starts_at:
            raise ValidationError(
                'The event has started, so this place can '
                'no longer be cancelled.', code='started',
            )
        # One UPDATE that only matches an active row: of two
        # requests, at most one changes it.
        changed = Registration.objects.filter(
            pk=self.pk, status=self.Status.ACTIVE
        ).update(status=self.Status.CANCELLED,
                 cancelled_at=now)
        self.refresh_from_db(fields=['status', 'cancelled_at'])
        return changed == 1

    def is_late(self):
        """Return whether it was cancelled after the deadline."""
        deadline = self.event.cancellation_deadline
        return (self.cancelled_at is not None
                and deadline is not None
                and self.cancelled_at >= deadline)

cancel() does not read the place’s status and then save it. It sends one UPDATE whose WHERE clause matches only an active row, and the database answers with the number of rows it changed. Of two requests, the first changes one row and the second none, whatever their copies said, so the count of places drops by exactly one. refresh_from_db() then loads what the database now holds, and the return value tells the view which message to show. is_late() works lateness out each time it is asked, so no field can disagree with the deadline.

uv run python manage.py test registrations -k CancelTests
Found 7 test(s).
Creating test database for alias 'default'...
...
Ran 7 tests in ...s

OK
Destroying test database for alias 'default'...

The life of a place, from register to cancel and back, is drawn in Figure 31.2.

A green Active card on the left, counted as a place taken, with two elbow arrows to grey cards in the middle: Cancelled, cancel() before the deadline, kept but not counted; and Cancelled late, cancel() from the deadline until the start. From each grey card an arrow leads to a green Active again card on the right: register() while open makes a new row. A grey note below says lateness is read from cancelled_at and the deadline, no field stores it, and there is at most one active row per member and event.
Figure 31.2 — The life of a place.

Common Error: “CHECK constraint failed: cancelled_at_matches_status”

Cancel a place by setting status = 'cancelled' and saving, without cancelled_at, and the database refuses the save with an IntegrityError naming Chapter 21’s rule cancelled_at_matches_status: a cancelled place must say when. Set both together, as cancel() does in one UPDATE.

The clinic’s times are drawn on one line in Figure 31.3.

A horizontal timeline with four marks: Opens, 14 days before, optional; Deadline, 2 days before; Closes, 1 day before; Start. Above it a green band from Opens to Closes reads Register: from opening, included, to closing, excluded. Below that a blue band from Opens to Deadline reads Cancel on time, and an orange band from Deadline to Start reads Cancel: counts as late. A grey note says closing and the deadline are needed to publish and are never after the start, and times are typed in the event’s own zone.
Figure 31.3 — The clinic’s times on one line.

Step 8: The Register button and the phone page

Tests first. Add at the end of registrations/tests.py:

def soon(**changes):
    """Create a clinic next week, open for registration now."""
    starts = timezone.now() + timedelta(days=7)
    return clinic(**{
        'starts_at': starts,
        'ends_at': starts + timedelta(hours=2),
        'registration_opens_at': None,
        'registration_closes_at': starts - timedelta(days=1),
        'cancellation_deadline': starts - timedelta(days=2),
    } | changes)


def url(name, *args):
    """Return the address of a registrations page."""
    return reverse(f'registrations:{name}', args=args)


class RegisterPageTests(TestCase):
    """The Register button and what it says back."""

    @classmethod
    def setUpTestData(cls):
        cls.event = soon()
        cls.sai = verified('sai@example.org')

    def test_a_visitor_signs_in_and_comes_back(self):
        page = self.event.get_absolute_url()
        response = self.client.get(page)
        sign_in = reverse('account_login')
        self.assertContains(
            response, f'href="{sign_in}?next={page}"'
        )
        self.assertNotContains(response, 'shares your name')
        self.sai.set_password(PASSWORD)
        self.sai.save()
        response = self.client.post(
            f'{sign_in}?next={page}',
            {'login': 'sai@example.org', 'password': PASSWORD},
        )
        self.assertRedirects(response, page,
                             fetch_redirect_response=False)

    def test_a_member_registers_with_one_post(self):
        self.client.force_login(self.sai)
        page = self.client.get(self.event.get_absolute_url())
        self.assertContains(page, 'phone number with this')
        response = self.client.post(
            url('register', self.event.pk), follow=True
        )
        self.assertRedirects(response,
                             self.event.get_absolute_url())
        self.assertContains(response, 'You have a place')
        self.assertEqual(self.event.places_taken(), 1)

    def test_register_is_post_only(self):
        self.client.force_login(self.sai)
        response = self.client.get(
            url('register', self.event.pk)
        )
        self.assertEqual(response.status_code, 405)
        self.assertFalse(Registration.objects.exists())

    def test_two_posts_make_one_place(self):
        self.client.force_login(self.sai)
        address = url('register', self.event.pk)
        self.client.post(address)
        response = self.client.post(address, follow=True)
        self.assertContains(response,
                            'You already have a place.')
        self.assertEqual(self.event.places_taken(), 1)

    def test_a_full_event_shows_why(self):
        for email in ('raj@example.org', 'soni@example.org'):
            self.event.registrations.create(
                member=verified(email)
            )
        self.client.force_login(self.sai)
        page = self.client.get(self.event.get_absolute_url())
        self.assertContains(page, 'This event is full.')
        self.assertNotContains(page,
                               url('register', self.event.pk))
        response = self.client.post(
            url('register', self.event.pk), follow=True
        )
        self.assertContains(response, 'This event is full.')
        self.assertEqual(self.event.places_taken(), 2)

    def test_an_unconfirmed_member_is_sent_to_confirm(self):
        soni = User.objects.create_user(
            'soni@example.org', display_name='Soni'
        )
        self.client.force_login(soni)
        page = self.client.get(self.event.get_absolute_url())
        self.assertContains(
            page, 'Confirm your email address to register.'
        )
        self.assertContains(page, reverse('account_email'))
        self.client.post(url('register', self.event.pk))
        self.assertFalse(Registration.objects.exists())

    def test_a_hidden_draft_is_missing(self):
        draft = soon(status=Event.Status.DRAFT)
        self.client.force_login(self.sai)
        response = self.client.post(url('register', draft.pk))
        self.assertEqual(response.status_code, 404)
        self.assertFalse(Registration.objects.exists())


class PhonePageTests(TestCase):
    """An event that asks for a phone number."""

    @classmethod
    def setUpTestData(cls):
        cls.event = soon(phone_required=True)
        cls.sai = verified('sai@example.org')

    def setUp(self):
        self.client.force_login(self.sai)

    def test_the_page_asks_for_the_number(self):
        page = self.client.get(self.event.get_absolute_url())
        self.assertContains(
            page, f'href="{url("phone", self.event.pk)}"'
        )
        response = self.client.post(
            url('register', self.event.pk)
        )
        self.assertRedirects(response,
                             url('phone', self.event.pk))
        self.assertFalse(Registration.objects.exists())

    def test_a_bad_number_saves_nothing(self):
        response = self.client.post(
            url('phone', self.event.pk), {'phone': '12345'}
        )
        self.assertContains(response, 'Enter a valid phone')
        self.assertFalse(Registration.objects.exists())
        self.assertFalse(Profile.objects.exists())

    def test_the_number_is_kept_and_the_place_made(self):
        response = self.client.post(
            url('phone', self.event.pk),
            {'phone': '98765 43210'},
        )
        self.assertRedirects(response,
                             self.event.get_absolute_url(),
                             fetch_redirect_response=False)
        self.assertEqual(Profile.of(self.sai).phone,
                         '+919876543210')
        self.assertEqual(self.event.places_taken(), 1)

The first test signs Sai in through allauth’s real form, with the next address the button gives, and checks that she comes back to the event page. test_two_posts_make_one_place sends Register twice in a row, as a double click would.

uv run python manage.py test registrations -k Page
Found 10 test(s).
Creating test database for alias 'default'...
...
KeyError: 'registrations'
Ran 10 tests in ...s

FAILED (failures=4, errors=6)
Destroying test database for alias 'default'...

The phone page needs a form. In accounts/forms.py, add after ProfileForm:

class PhoneForm(forms.Form):
    """The phone number an event asks for, once."""

    phone = PhoneNumberField(
        label='Phone number', help_text=PHONE_HELP,
    )

    def save(self, user):
        """Keep the number on the member's Profile."""
        profile = Profile.of(user)
        profile.phone = self.cleaned_data['phone']
        profile.full_clean()
        profile.save(update_fields=['phone'])

Here the field is required: the member came to this page to give the number. Replace the generated registrations/views.py with:

"""Pages for members' places and organizers' lists."""
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ValidationError
from django.shortcuts import (
    get_object_or_404, redirect, render,
)
from django.utils import timezone
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

from .models import Registration

Action = AuditEvent.Action


def event_for(request, event_id):
    """Return the event if the viewer may see it, or 404."""
    event = get_object_or_404(Event, pk=event_id)
    if not event.is_visible_to(request.user):
        deny(request, Action.VIEW_EVENT, event, hidden=True)
    return event


def take_place(request, event):
    """Register the member, then say what happened."""
    try:
        event.register(request.user, timezone.now())
    except ValidationError as error:
        codes = [e.code for e in error.error_list]
        if codes == ['phone_missing']:
            return redirect('registrations:phone', event.pk)
        if codes == ['already_registered']:
            messages.info(request, REASONS['already_registered'])
        else:
            for message in error.messages:
                messages.error(request, message)
    else:
        messages.success(request, 'You have a place.')
    return redirect(event)


@require_POST
@login_required
def register(request, event_id):
    """Register the signed-in member for the event."""
    return take_place(request, event_for(request, event_id))


@require_http_methods(['GET', 'POST'])
@login_required
def register_phone(request, event_id):
    """Ask for the number the event needs, then register."""
    event = event_for(request, event_id)
    form = PhoneForm(request.POST or None)
    if form.is_valid():
        form.save(request.user)
        return take_place(request, event)
    return render(request, 'registrations/phone.html',
                  {'event': event, 'form': form})

event_for() refuses an event the viewer may not see, with Chapter 30’s deny(), so a draft’s number reveals nothing here either. take_place() is the one place a registration is attempted. It passes the current time, and reads the codes from the refusal: a missing phone number alone sends the member to the phone page; a place already held is good news, shown as information; anything else is shown as errors. register() accepts POST only and needs a signed-in member. register_phone() shows the form on GET; on a valid POST it keeps the number, then registers exactly as the button does.

Create registrations/urls.py:

"""Addresses of the registrations app's pages."""
from django.urls import path

from . import views

app_name = 'registrations'

urlpatterns = [
    path('events/<int:event_id>/register/',
         views.register, name='register'),
    path('events/<int:event_id>/register/phone/',
         views.register_phone, name='phone'),
]

and include it in config/urls.py, after the events line:

    path('', include('registrations.urls')),

The event page shows the button. In events/views.py, import REASONS:

from .models import REASONS, Event, OrganizerAssignment

and replace event_detail() with it and a helper:

def event_detail(request, event_id):
    """Show an event its viewer may see, or 404."""
    event = get_object_or_404(
        Event.objects.with_places(), pk=event_id
    )
    if not event.is_visible_to(request.user):
        deny(request, Action.VIEW_EVENT, event, hidden=True)
    now = timezone.now()
    return render(request, 'events/detail.html', {
        'event': event,
        'now': now,
        'can_edit': event.can_be_edited_by(request.user),
    } | registration_panel(event, request.user, now))


def registration_panel(event, user, now):
    """Return what the event page says about registering."""
    if not user.is_authenticated:
        codes = event.open_problems(now)
        return {'reasons': [REASONS[c] for c in codes]}
    place = event.place_of(user)
    codes = [] if place else event.registration_problems(
        user, now
    )
    return {
        'place': place,
        'reasons': [REASONS[c] for c in codes
                    if c != 'phone_missing'],
        'needs_phone': 'phone_missing' in codes,
        'unverified': 'unverified' in codes,
    }

registration_panel() decides what the page says. A visitor sees the reasons that apply to everyone; a member sees their place, or their own reasons. The phone reason is kept apart, because for it the page shows the button anyway, leading to the phone page.

Create three templates in a new folder, registrations/templates/registrations/. First the sharing notice, sharing.html, used beside every Register button:

<p class="text-sm">Registering shares your name, email
  address, and phone number with this event's
  organizers.</p>

the phone page, phone.html:

{% extends "base.html" %}

{% block title %}Your phone number | Otahque{% endblock %}

{% block content %}
  <h1>{{ event.title }} asks for a phone number</h1>
  <p>Otahque keeps it on your profile, so you are asked
     only once. You can change it there.</p>
  {% include "registrations/sharing.html" %}
  <form method="post" class="card space-y-4 border
        border-base-300 bg-base-100 p-6">
    {% csrf_token %}
    {{ form }}
    <button type="submit" class="btn btn-primary">
      Save and register</button>
  </form>
  <p>
    <a href="{{ event.get_absolute_url }}">Back to the
      event</a>
  </p>
{% endblock %}

and the panel itself, panel.html:

<section class="space-y-3 border-t border-base-300 pt-4"
         aria-label="Registration">
  {% if place %}
    <p><span class="badge badge-success">You have a
      place</span> Registered
      {{ place.registered_at|date:"j M Y, H:i" }}.</p>
  {% elif reasons %}
    <ul class="list-disc pl-5">
      {% for reason in reasons %}
        <li>{{ reason }}</li>
      {% endfor %}
    </ul>
    {% if unverified %}
      <p><a href="{% url 'account_email' %}">Confirm your
        email address</a>, then come back.</p>
    {% endif %}
  {% elif not user.is_authenticated %}
    {% url 'account_login' as sign_in %}
    {% with back=event.get_absolute_url|urlencode %}
      <a class="btn btn-primary"
         href="{{ sign_in }}?next={{ back }}">
        Sign in to register</a>
    {% endwith %}
  {% elif needs_phone %}
    <a class="btn btn-primary"
       href="{% url 'registrations:phone' event.pk %}">
      Register</a>
    {% include "registrations/sharing.html" %}
  {% else %}
    <form method="post"
          action="{% url 'registrations:register' event.pk %}">
      {% csrf_token %}
      <button type="submit" class="btn btn-primary">
        Register</button>
    </form>
    {% include "registrations/sharing.html" %}
  {% endif %}
</section>

The visitor’s link signs in and comes back with next set to the event page, not to the Register address. In events/templates/events/detail.html, include the panel after the organizers’ names:

    {% include "registrations/panel.html" %}
uv run python manage.py test registrations -k Page
Found 10 test(s).
Creating test database for alias 'default'...
...
Ran 10 tests in ...s

OK
Destroying test database for alias 'default'...

One earlier test counts the event page’s queries, and the panel added one: it counts the active places again, inside the rules, rather than trusting the figure shown above it.

uv run python manage.py test events.tests.PlacesLeftTests
Found 2 test(s).
Creating test database for alias 'default'...
...
AssertionError: 3 != 2 : 3 queries executed, 2 expected
Ran 2 tests in ...s

FAILED (failures=1)
Destroying test database for alias 'default'...

In events/tests.py, in PlacesLeftTests.test_pages_show_places_left, change the event page’s count from 2 to 3:

        self.assertNotContains(response, 'of 5 places left')
        # The registration panel counts places again.
        with self.assertNumQueries(3):
uv run python manage.py test events.tests.PlacesLeftTests
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s

OK
Destroying test database for alias 'default'...

Common Error: 405 after signing in

Make the visitor’s link point at the Register address itself, or let login_required send a visitor there, and sign-in brings them back with a GET to an address that accepts only POST: “405 Method Not Allowed”. A POST cannot be repeated after a redirect. Send visitors back to the event page, where the button is, as panel.html does.

Step 9: My registrations and the cancel page

Tests first. Add at the end of registrations/tests.py:

class MyRegistrationsTests(TestCase):
    """A member's own places, and only theirs."""

    @classmethod
    def setUpTestData(cls):
        cls.event = soon()
        cls.sai = verified('sai@example.org')
        cls.raj = verified('raj@example.org')
        now = timezone.now()
        cls.sais = cls.event.register(cls.sai, now)
        cls.rajs = cls.event.register(cls.raj, now)

    def test_the_page_lists_upcoming_places(self):
        self.client.force_login(self.sai)
        response = self.client.get(url('mine'))
        self.assertContains(response, 'Django clinic')
        self.assertContains(response,
                            url('cancel', self.sais.pk))
        self.assertNotContains(response,
                               url('cancel', self.rajs.pk))

    def test_a_late_cancel_is_marked(self):
        self.client.force_login(self.raj)
        Event.objects.filter(pk=self.event.pk).update(
            cancellation_deadline=timezone.now()
        )
        response = self.client.post(
            url('cancel', self.rajs.pk), follow=True
        )
        self.assertContains(response, 'late cancellation')
        late = '<span class="badge">Cancelled late</span>'
        self.assertContains(response, late, html=True)

    def test_confirm_then_cancel(self):
        self.client.force_login(self.sai)
        address = url('cancel', self.sais.pk)
        page = self.client.get(address)
        self.assertContains(page, 'Cancel my place')
        self.assertEqual(self.event.places_taken(), 2)
        response = self.client.post(address)
        self.assertRedirects(response, url('mine'),
                             fetch_redirect_response=False)
        self.assertEqual(self.event.places_taken(), 1)
        again = self.client.post(address, follow=True)
        self.assertContains(again,
                            'This place was already cancelled.')
        self.assertEqual(self.event.places_taken(), 1)

    def test_someone_elses_place_is_missing(self):
        self.client.force_login(self.sai)
        address = url('cancel', self.rajs.pk)
        for response in (self.client.get(address),
                         self.client.post(address)):
            self.assertEqual(response.status_code, 404)
        self.rajs.refresh_from_db()
        self.assertEqual(self.rajs.status, 'active')
        refused = AuditEvent.objects.filter(
            action='cancel_registration', outcome='refused',
            actor=self.sai, target_id=self.rajs.pk,
        )
        self.assertEqual(refused.count(), 2)

    def test_a_visitor_is_sent_to_sign_in(self):
        response = self.client.get(url('mine'))
        self.assertRedirects(
            response,
            f"{reverse('account_login')}?next={url('mine')}",
            fetch_redirect_response=False,
        )

test_someone_elses_place_is_missing is Sai typing the number of Raj’s place: GET and POST both answer 404, Raj’s place stays active, and both attempts are recorded.

uv run python manage.py test registrations -k MyRegistrations
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s

FAILED (errors=5)
Destroying test database for alias 'default'...

The audit trail needs two new actions. In audit/models.py, add to AuditEvent.Action, after LEAVE_ORGANIZERS:

        VIEW_ATTENDEES = (
            'view_attendees', 'Open an attendee list'
        )
        CANCEL_REGISTRATION = (
            'cancel_registration', 'Cancel a registration'
        )

The command is split; in PowerShell the backtick continues it, with no space after it:

uv run python manage.py makemigrations audit `
  --name registration_actions

In Git Bash, macOS, Linux, or WSL, the backslash does the same:

uv run python manage.py makemigrations audit \
  --name registration_actions
Migrations for 'audit':
  audit/migrations/0002_registration_actions.py
    ~ Alter field action on auditevent

Then run uv run python manage.py migrate. The migration changes only the field’s list of choices; no table changes. Add the views at the end of registrations/views.py:

@login_required
def my_registrations(request):
    """Show the signed-in member's places, upcoming first."""
    now = timezone.now()
    mine = request.user.registrations.select_related('event')
    current = mine.active().filter(event__ends_at__gt=now)
    earlier = mine.exclude(pk__in=current)
    return render(request, 'registrations/mine.html', {
        'current': current.order_by('event__starts_at'),
        'earlier': earlier.order_by('-event__starts_at',
                                    '-registered_at'),
        'now': now,
    })


@require_http_methods(['GET', 'POST'])
@login_required
def cancel_registration(request, registration_id):
    """Confirm, then cancel the member's own place."""
    registration = get_object_or_404(
        Registration.objects.select_related('event'),
        pk=registration_id,
    )
    if registration.member_id != request.user.pk:
        # Someone else's place: answered as if missing.
        deny(request, Action.CANCEL_REGISTRATION,
             registration, hidden=True)
    now = timezone.now()
    if request.method == 'POST':
        try:
            changed = registration.cancel(now)
        except ValidationError as error:
            messages.error(request, error.messages[0])
        else:
            say_cancelled(request, registration, changed)
        return redirect('registrations:mine')
    event = registration.event
    deadline = event.cancellation_deadline
    return render(request, 'registrations/cancel.html', {
        'registration': registration,
        'event': event,
        'started': now >= event.starts_at,
        'late': deadline is not None and now >= deadline,
    })


def say_cancelled(request, registration, changed):
    """Tell the member what their cancel request did."""
    if not changed:
        messages.info(request,
                      'This place was already cancelled.')
    elif registration.is_late():
        messages.success(request, 'Place cancelled. It '
                         'counts as a late cancellation.')
    else:
        messages.success(request, 'Place cancelled.')

my_registrations() reads through request.user.registrations, so only the member’s own places can appear; no number from the address is involved. cancel_registration() does take a number from the address, so it checks the owner itself and refuses others with 404, recorded. On POST it cancels and redirects to My registrations; on GET it shows whether cancelling now would be late. Add both addresses to registrations/urls.py, before the closing ]:

    path('registrations/', views.my_registrations,
         name='mine'),
    path('registrations/<int:registration_id>/cancel/',
         views.cancel_registration, name='cancel'),

Create registrations/templates/registrations/mine.html:

{% extends "base.html" %}

{% block title %}My registrations | Otahque{% endblock %}

{% block content %}
  <h1>My registrations</h1>
  <h2>Upcoming</h2>
  <ul class="space-y-3">
    {% for place in current %}
      {% include "registrations/row.html" %}
    {% empty %}
      <li>No upcoming places.
        <a href="{% url 'events:list' %}">Find an
          event</a>.</li>
    {% endfor %}
  </ul>
  <h2 class="mt-8">Earlier and cancelled</h2>
  <ul class="space-y-3">
    {% for place in earlier %}
      {% include "registrations/row.html" %}
    {% empty %}
      <li>Nothing yet.</li>
    {% endfor %}
  </ul>
{% endblock %}

one row, row.html, shared by both lists:

<li class="space-y-1">
  <a href="{{ place.event.get_absolute_url }}">
    {{ place.event.title }}</a>
  <span class="block text-sm">
    {% include "events/when.html" with event=place.event %}
  </span>
  {% if place.event.status == 'cancelled' %}
    <span class="badge badge-error">Event cancelled</span>
  {% endif %}
  {% if place.status == 'cancelled' and place.is_late %}
    <span class="badge">Cancelled late</span>
  {% elif place.status == 'cancelled' %}
    <span class="badge">Cancelled</span>
  {% elif now < place.event.starts_at %}
    <a href="{% url 'registrations:cancel' place.pk %}">
      Cancel my place</a>
  {% endif %}
</li>

and the confirmation page, cancel.html:

{% extends "base.html" %}

{% block title %}Cancel your place | Otahque{% endblock %}

{% block content %}
  <h1>Cancel your place at {{ event.title }}?</h1>
  {% if registration.status == 'cancelled' %}
    <p>This place is already cancelled.</p>
  {% elif started %}
    <p>The event has started, so this place can no longer
       be cancelled.</p>
  {% else %}
    <p>Your place is released for someone else. If
       registration has closed, you cannot take it
       back.</p>
    {% if late %}
      <p class="rounded-box border border-base-content
                px-3 py-1 text-sm">
        The cancellation deadline has passed, so this
        counts as a late cancellation.</p>
    {% endif %}
    <form method="post" class="card space-y-4 border
          border-base-300 bg-base-100 p-6">
      {% csrf_token %}
      <button type="submit" class="btn btn-error">
        Cancel my place</button>
    </form>
  {% endif %}
  <p>
    <a href="{% url 'registrations:mine' %}">Back to my
      registrations</a>
  </p>
{% endblock %}

In templates/includes/site_nav.html, add the menu link before the profile link, inside {% if user.is_authenticated %}:

      <a href="{% url 'registrations:mine' %}">
        My registrations</a>

and in panel.html, add the cancel link after the “Registered” line:

    <p><a href="{% url 'registrations:cancel' place.pk %}">
      Cancel my place</a></p>
uv run python manage.py test registrations -k MyRegistrations
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s

OK
Destroying test database for alias 'default'...

Step 10: The attendee list

Tests first. Add at the end of registrations/tests.py:

class AttendeeListTests(TestCase):
    """Sam's attendee list: who has a place, and contacts."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = in_group('sam@example.org', ORGANIZERS)
        cls.event = soon()
        cls.event.add_organizer(cls.sam)
        cls.sai = verified('sai@example.org')
        Profile.objects.create(user=cls.sai,
                               phone='+919876543210')
        cls.event.register(cls.sai, timezone.now())

    def test_the_list_shows_contacts_and_counts(self):
        raj = verified('raj@example.org')
        self.event.register(raj, timezone.now()).cancel(
            timezone.now()
        )
        self.client.force_login(self.sam)
        response = self.client.get(
            url('attendees', self.event.pk)
        )
        for text in ('Sai', 'sai@example.org',
                     '+91 98765 43210', 'Cancellations: 1',
                     'late: 0'):
            self.assertContains(response, text)
        self.assertNotContains(response, 'raj@example.org')

    def test_a_fixed_number_of_queries(self):
        self.client.force_login(self.sam)
        address = url('attendees', self.event.pk)
        with CaptureQueriesContext(connection) as one:
            self.client.get(address)
        for email in ('raj@example.org', 'soni@example.org'):
            self.event.registrations.create(
                member=verified(email)
            )
        with CaptureQueriesContext(connection) as three:
            self.client.get(address)
        self.assertEqual(len(three), len(one))

    def test_contacts_stay_off_the_event_page(self):
        soni = verified('soni@example.org')
        self.client.force_login(soni)
        page = self.client.get(self.event.get_absolute_url())
        self.assertNotContains(page, 'sai@example.org')
        self.assertNotContains(page, 'Attendee list')
        self.client.force_login(self.sam)
        page = self.client.get(self.event.get_absolute_url())
        self.assertContains(page, 'Attendee list')

test_a_fixed_number_of_queries counts the page’s queries with one attendee and again with three, and expects the same number. It does not fix the number itself, so a change to the page’s other queries does not break it.

uv run python manage.py test registrations -k AttendeeList
Found 3 test(s).
Creating test database for alias 'default'...
...
AssertionError: False is not true : Couldn't find 'Attendee
    list' in the following response
Ran 3 tests in ...s

FAILED (failures=1, errors=2)
Destroying test database for alias 'default'...

Chapter 22 left this method for the first page that shows names. In registrations/models.py, add to RegistrationQuerySet, after active():

    def with_people(self):
        """Fetch each place's member and profile at once."""
        return self.select_related('member', 'member__profile')

select_related() joins the member and their profile into the same query, so the list reads every name, email, and phone from one result instead of asking once per person. member__profile follows the one-to-one link from a user to their Profile; a member with no profile simply has none.

In events/models.py, add who may open the list, after can_be_edited_by():

    def can_see_attendees(self, user):
        """Return whether user may open the attendee list.

        Its current organizers may, and the administrator
        (registrations.view_registration).
        """
        if self.has_organizer(user):
            return True
        return user.has_perm(
            'registrations.view_registration'
        )

Add the view at the end of registrations/views.py:

@login_required
def attendees(request, event_id):
    """Show the attendee list to the event's organizers."""
    event = get_object_or_404(Event, pk=event_id)
    if not event.is_visible_to(request.user):
        deny(request, Action.VIEW_ATTENDEES, event,
             hidden=True)
    if not event.can_see_attendees(request.user):
        deny(request, Action.VIEW_ATTENDEES, event)
    places = event.registrations.active().with_people()
    return render(request, 'registrations/attendees.html', {
        'event': event,
        'places': places,
        'counts': event.registrations.cancellation_counts(),
    })

and its address at the end of urlpatterns in registrations/urls.py:

    path('events/<int:event_id>/registrations/',
         views.attendees, name='attendees'),

Create registrations/templates/registrations/attendees.html:

{% extends "base.html" %}

{% block title %}Attendees of {{ event.title }} |
  Otahque{% endblock %}

{% block content %}
  <h1>Attendees of {{ event.title }}</h1>
  <p>{{ places|length }} of {{ event.capacity }} places
     taken. Cancellations: {{ counts.cancelled }}, of
     which late: {{ counts.late }}.</p>
  <p class="text-sm">Contact details are for running this
     event only. Do not copy them elsewhere.</p>
  {% if places %}
    <div class="overflow-x-auto">
      <table class="table">
        <thead>
          <tr>
            <th scope="col">Name</th>
            <th scope="col">Email</th>
            <th scope="col">Phone</th>
            <th scope="col">Registered</th>
          </tr>
        </thead>
        <tbody>
          {% for place in places %}
            {% with person=place.member %}
            <tr>
              <td>{{ person.display_name }}</td>
              <td>{{ person.email }}</td>
              {% with phone=person.profile.phone %}
              <td>
                {{ phone.as_international|default:"Not given" }}
              </td>
              {% endwith %}
              <td>{{ place.registered_at|date:"j M Y, H:i" }}
              </td>
            </tr>
            {% endwith %}
          {% endfor %}
        </tbody>
      </table>
    </div>
  {% else %}
    <p>Nobody has a place yet.</p>
  {% endif %}
  <p>
    <a href="{{ event.get_absolute_url }}">Back to the
      event</a>
  </p>
{% endblock %}

places|length runs the query once and the loop reuses its rows. The table sits in a box that scrolls sideways on a phone, so the page itself never does. The page reminds organizers what the details are for. Give organizers the link: in panel.html, add before the closing </section>:

  {% if can_see_attendees %}
    <p><a href="{% url 'registrations:attendees' event.pk %}">
      Attendee list</a></p>
  {% endif %}

and in events/views.py, add one line to the dictionary registration_panel() returns for members, after 'unverified':

        'can_see_attendees': event.can_see_attendees(user),

The new templates use classes the stylesheet does not have yet, such as table and badge-success. Chapter 14’s build reads only the folders listed in static/otahque/source.css, so add the new one after the events line:

@source "../../registrations/templates";

and rebuild the stylesheet:

npm run build
uv run python manage.py test registrations -k AttendeeList
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s

OK
Destroying test database for alias 'default'...

Who sees what about places is summed up in Figure 31.4.

Three cards side by side. A blue card, Sai, a member: her own places on My registrations, and another member’s place answers 404 and is recorded. A green card, Sam, organizer: the attendee list of his event with names, emails, phones, times, and cancellation counts. A red card, Raj, Delhi organizer: Sam’s list answers 403 for a published event and 404 for a draft, recorded. A grey note below says the administrator may also open the list, no other page shows anyone’s email or phone, and members are told before registering.
Figure 31.4 — Who sees what about places.

Common Error: one query per attendee

Write the view with event.registrations.active() alone, and the page still works, but each place.member and each person.profile is fetched when the template reaches it: two extra queries per attendee, two hundred for a hundred people. test_a_fixed_number_of_queries fails with different counts for one and three attendees. Use with_people().

Step 11: The matrix rows

Chapter 30 listed two planned rows for this chapter. Members’ own places are tested in Step 9; the attendee list gets a matrix of its own. Add at the end of registrations/tests.py:

# Who may open the attendee list (Chapter 31).
ATTENDEE_MATRIX = [
    # person, Sam's published event, Sam's draft
    ('visitor', 'sign in', 'sign in'),
    ('member', '403', '404'),
    ('staff only', '403', '404'),
    ('other organizer', '403', '404'),
    ('administrator', 'ok', 'ok'),
    ('superuser', 'ok', 'ok'),
    ('organizer', 'ok', 'ok'),
]


class AttendeeMatrixTests(TestCase):
    """Each person against the attendee list."""

    @classmethod
    def setUpTestData(cls):
        sam = in_group('sam@example.org', ORGANIZERS)
        raj = in_group('raj@example.org', ORGANIZERS)
        cls.events = [soon(), soon(status='draft')]
        for event in cls.events:
            event.add_organizer(sam)
        soon(title='Delhi clinic').add_organizer(raj)
        cls.people = {
            'visitor': None,
            'member': verified('sai@example.org'),
            'staff only': User.objects.create_user(
                'staff@example.org', display_name='Staff',
                is_staff=True,
            ),
            'other organizer': raj,
            'administrator': in_group(
                'admin@example.org', 'Administrators',
                is_staff=True,
            ),
            'superuser': User.objects.create_superuser(
                'root@example.org', display_name='Root'
            ),
            'organizer': sam,
        }

    def test_every_row(self):
        for person, *expected in ATTENDEE_MATRIX:
            self.client.logout()
            if self.people[person]:
                self.client.force_login(self.people[person])
            with self.subTest(person=person):
                answers = [outcome(self.client.get(
                    url('attendees', event.pk)))
                    for event in self.events]
                self.assertEqual(answers, expected)

    def test_refusals_are_recorded(self):
        raj = self.people['other organizer']
        self.client.force_login(raj)
        for event in self.events:
            self.client.get(url('attendees', event.pk))
        refused = AuditEvent.objects.filter(
            action='view_attendees', outcome='refused',
            actor=raj,
        )
        self.assertEqual(refused.count(), 2)
uv run python manage.py test registrations -k AttendeeMatrix
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s

OK
Destroying test database for alias 'default'...

The code already exists, so the matrix passes at once: it proves each row, including the people who must be refused. In docs/design/permissions.md, replace the “Planned rows” heading and its Chapter 31 item with:

## Registrations (Chapter 31)

- A member registers, sees, and cancels only their own
  places. Another member's place: 404, and the attempt
  is recorded.
- The attendee list shows contact details, so only the
  event's current organizers and the administrator
  (registrations.view_registration) may open it:

| Person          | Published event | Draft   |
|-----------------|-----------------|---------|
| Visitor         | sign in         | sign in |
| Member          | 403             | 404     |
| Staff only      | 403             | 404     |
| Other organizer | 403             | 404     |
| Administrator   | ok              | ok      |
| Superuser       | ok              | ok      |
| Organizer       | ok              | ok      |

Proved by AttendeeMatrixTests. See registration.md.

## Planned rows

- Chapter 46:

Step 12: Check and commit

The data model gained fields, so update the ERD from Chapter 15. In docs/design/erd.md, add the phone to PROFILE:

        text timezone "IANA name, blank = not set"
        text phone "E.164, blank = not given"
    }

the times and the setting to EVENT:

        text status "draft, published, cancelled"
        datetime registration_opens_at "blank = on publication"
        datetime registration_closes_at "needed to publish"
        datetime cancellation_deadline "needed to publish"
        bool phone_required
    }

the new rules after the time-order rule:

- A cancellation is never earlier than its registration,
  and a revocation never earlier than its assignment
  (CHECK constraints).
- Registration opens before it closes; closing and the
  cancellation deadline are no later than the start
  (CHECK constraints, Chapter 31).

and answer two open questions:

## Open questions

- Who appoints organizers, and must an event have one?
- What happens to active registrations when an event
  is cancelled? (Chapter 26: they stay as they are;
  Chapters 43-44 decide what members are told.)

Answered in Chapter 31: contact details are the email
and an optional phone number on the Profile, which an
event may require; registration times are on Event.

Then check that no model change lacks a migration, and run everything:

uv run python manage.py makemigrations --check --dry-run
No changes detected
uv run python manage.py test
Found 342 test(s).
Creating test database for alias 'default'...
...
Ran 342 tests in ...s

OK
Destroying test database for alias 'default'...

Walk through it in the browser, with a private window for each person. As Sam, publish a clinic with a closing time and a deadline, and tick “Ask for a phone number”. As a visitor, open it: “Sign in to register”. Sign up as Sai, confirm the address from the email in the terminal, register, give a phone number, and see “You have a place”. Open My registrations and cancel; register again. As Raj, after the deadline, cancel: “Cancelled late”. As Sam, open the attendee list. Then commit:

git add .
git status --short
M  accounts/forms.py
A  accounts/migrations/0005_profile_phone.py
M  accounts/models.py
M  accounts/tests.py
M  accounts/views.py
A  audit/migrations/0002_registration_actions.py
M  audit/models.py
M  config/settings.py
M  config/tests.py
M  config/urls.py
M  docs/design/erd.md
M  docs/design/event-states.md
M  docs/design/permissions.md
A  docs/design/registration.md
M  events/admin.py
M  events/forms.py
A  events/migrations/0006_registration.py
A  events/migrations/0007_fill_window.py
M  events/models.py
M  events/templates/events/detail.html
M  events/tests.py
M  events/views.py
M  pyproject.toml
A  registrations/migrations/0003_constraint_code.py
M  registrations/models.py
A  registrations/templates/registrations/attendees.html
A  registrations/templates/registrations/cancel.html
A  registrations/templates/registrations/mine.html
A  registrations/templates/registrations/panel.html
A  registrations/templates/registrations/phone.html
A  registrations/templates/registrations/row.html
A  registrations/templates/registrations/sharing.html
M  registrations/tests.py
A  registrations/urls.py
M  registrations/views.py
M  static/otahque/site.css
M  static/otahque/source.css
M  templates/includes/site_nav.html
M  uv.lock
git commit -m "Add registration, cancellation, and attendees"

When something goes wrong

Table 31.2 — Recovery for Chapter 31
Symptom Likely cause Recovery
"Event has no field named 'registration_opens_at'" The fields are not in Event yet, or the file was not saved Add Step 3's fields; run makemigrations again
IntegrityError naming event_closes_by_start A time after the start, saved past the form Correct the time; the form shows the rule's message
"No module named 'phonenumber_field'" uv add did not finish, or another environment is active Run uv add again; run commands through uv run
Published events still have no closing time Migration 0007 was left empty Copy m_fill's body into it; migrate events 0006, then migrate
TransactionManagementError in register() The try is not around its own inner atomic() Wrap only the insert in atomic(); catch outside it
NoReverseMatch for 'registrations:cancel' The panel links to a page whose address is not added yet Add Step 9's addresses, or move the link to Step 9
405 after signing in from an event The sign-in link's next is the Register address Use the event page's address as next
A refused member sees no message base.html shows no messages, or the view returned without one Compare base.html with Chapter 24; check take_place()
The attendee list makes many queries The view does not use with_people() Add with_people() to the queryset
New pages look unstyled The stylesheet was not rebuilt with the new folder Add the @source line; run npm run build

To compare without losing your own work, build a fresh copy of the Chapter 30 checkpoint in another folder, apply this chapter’s listings there, and compare the files with yours. Nothing in this chapter asks you to reset or delete your database or your commits.

PAGE 003

Verify Your Work

Work through Table 31.3 from the folder that holds manage.py. For the browser rows, start the development server and use a private window for each person, so that no earlier session is sent.

Table 31.3 — Verification checklist for Chapter 31
Check Command or action Expected result
Starting point uv run python manage.py test Found 288 test(s); OK
Tests fail first Each step's new tests, before the code FAILED, AttributeError, or NoReverseMatch
Tests pass uv run python manage.py test Found 342 test(s); OK
No migration waiting makemigrations --check --dry-run No changes detected
Publishing needs times Publish a draft without a closing time "Set when registration closes."; still a draft
Visitor Open a published event, signed out "Sign in to register"; back on the event after sign-in
Register once Press Register twice One place; "You already have a place."
Unconfirmed email A new member presses Register "Confirm your email address to register." and a link
Phone asked An event with the phone setting The phone page; "12345" refused; a real number registers
Late cancel Cancel after the deadline "Cancelled late" on My registrations
Someone else's place Type another member's cancel address Page not found; a refused AuditEvent
Attendee list Sam, then Raj, open the list Sam: names, emails, phones, counts; Raj: 403
Phone width Device toolbar, 390 px No sideways page scroll; the table scrolls in its box
Committed git status --short No output
Not verified macOS, Linux, WSL; Firefox, Safari Readers on those systems

The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 30 checkpoint, with each listing applied in the order printed. The browser rows were walked through in Microsoft Edge at 390 px and 1280 px. Two overlapping requests for the last place were not tested: SQLite runs one writer at a time, so the case cannot be reproduced here (Chapter 33).

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 3 Why is the cancellation deadline required to publish, when members may cancel after it anyway?

Flip to check your answerFold answer back

Answer. The deadline does not stop cancelling; it decides how a cancellation is counted. Without it, Otahque could not say which cancellations were late, and Sam’s late count would mean nothing. Requiring it before publication means every published event can answer the question.

Que. 4 register() catches IntegrityError. Why does it look for the member’s place before answering “You already have a place”?

Flip to check your answerFold answer back

Answer. Because an IntegrityError can come from any database rule, not only registration_one_active. Finding the active place proves that the expected rule refused the insert, so the request was a repeat. If no place exists, the error had another cause, and it is raised again instead of being hidden behind a friendly message.

Que. 5 Two copies of Raj’s place are loaded by two requests, and both call cancel(). Why does the count drop by exactly one?

Flip to check your answerFold answer back

Answer. cancel() sends one UPDATE that matches only a row whose status is still active. The database changes the row for the first request and finds nothing to change for the second, whatever each copy in Python says. The second call returns False and the member is told the place was already cancelled.

Que. 6 The attendee list page is at /events/<id>/registrations/. Raj organizes another event. What does he get for Sam’s published event, and for Sam’s draft, and why the difference?

Flip to check your answerFold answer back

Answer. 403 for the published event, because anyone may see that event exists and Raj is simply not allowed to see its list. 404 for the draft, because Raj may not even know the draft exists, so the page answers as if there were none. Both attempts are recorded as refused view_attendees rows.

Mini-Challenge

Que. 7 When registration has not opened yet, the event page lists “Registration has not opened yet.” but does not say when it opens. Make the page say “Registration opens” followed by the time, in the event’s zone, and add a test. Run the test first and watch it fail.

Flip to check your answerFold answer back

Answer. In registrations/templates/registrations/panel.html, after the list of reasons (after </ul>), add:

    {% if now < event.registration_opens_at %}
      {% with at=event.registration_opens_at %}
      <p>Registration opens
        {% include "events/when.html" %}.</p>
      {% endwith %}
    {% endif %}

now is already in the event page’s context, and events/when.html shows a time in the event’s zone, with the viewer’s own time when it differs, as the start does. A comparison with a blank opening time is false in a template, so nothing shows for events without one. The test, at the end of registrations/tests.py:

class OpeningTimeTests(TestCase):
    """The event page says when registration opens."""

    def test_the_page_says_when_it_opens(self):
        later = timezone.now() + timedelta(days=1)
        event = soon(registration_opens_at=later)
        page = self.client.get(event.get_absolute_url())
        self.assertContains(page, 'Registration opens')
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s

OK
Destroying test database for alias 'default'...

What We Learned

  • A rule with several conditions is clearer as a list of named reasons, each with a stable code that tests and views compare.
  • Half-open windows include their opening and exclude their closing; tests pass the exact instants on either side.
  • Optional and required times can live on one model: NULL allowed in the database, required at publication, ordered by CHECK constraints with a branch for blanks.
  • A data migration fills existing rows, inside the database with F(), so old records keep their meaning under new rules.
  • An action belongs in a model method inside transaction.atomic(); a database rule stays the backstop for what a check can miss.
  • Catch an expected database error around its own inner atomic(), confirm it is the expected one, and raise anything else again.
  • One conditional UPDATE changes a row exactly once, however many requests try.
  • Register and Cancel are POST only; repeated requests show the result the member already has, and Post/Redirect/Get keeps refresh harmless.
  • Scoped lookups and an owner check answer someone else’s record with 404, and the attempt is recorded.
  • select_related() keeps a list of people at a fixed number of queries.
  • A phone number is stored once, in E.164, with a maintained library; members are told who will see their contact details.

Key terms

Use Table 31.4 to explain this chapter’s ideas in your own words.

Table 31.4 — Key terms from Chapter 31
Term Meaning
Named reason A short code and a message saying why an action was refused.
Half-open window A time range that includes its start and excludes its end.
Cancellation deadline The time from which a cancellation counts as late.
Late cancellation A cancellation made at or after the deadline, before the start.
Transaction A group of database changes kept or undone together.
Savepoint A mark inside a transaction that can be rolled back to on its own.
Backstop A database rule that holds when a check in code is skipped or raced.
Safe method An HTTP method, such as GET, that must not change anything.
Idempotent Giving the same result however many times it is repeated.
Conditional update An UPDATE whose WHERE clause matches only rows in the expected state.
E.164 The international phone number form: +, country code, number.
Attendee list The organizer's page of who holds a place, with contact details.

Readiness checkpoint: you are ready for Chapter 32 when all 342 tests pass, makemigrations --check --dry-run prints No changes detected, a draft without a closing time or deadline cannot be published, a member with a confirmed email registers once and only once, a member without a phone number is asked for it on an event that requires one, cancelling releases the place and shows “Cancelled late” after the deadline, another member’s place answers “not found”, Sam’s attendee list shows contact details that Raj cannot open, and the commit is made.

Git Commit

Your Chapter 31 work was committed in Step 12, with the message “Add registration, cancellation, and attendees”. It holds the registration times, the phone setting, and their rules on Event with two migrations, one of which fills existing events; the constraint code on registration_one_active; the phone number on Profile and the package that checks it; the registration rules, register(), cancel(), with_people(), and the cancellation counts; the registrations app’s views, addresses, and seven templates; the panel on the event page and the menu link; two new audit actions; the stylesheet rebuilt for the new templates; the design note and the updated permission, event-state, and ERD notes; five earlier tests updated in place; and fifty-four new tests.

PAGE 005

Test Your Knowledge: Interview Questions

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: attempt them now, and return after Chapter 33. They are extension questions, not a gate to the next chapter. Each code proof is a practice file run with uv run python manage.py shell -c "exec(open('NAME').read())"; each rolls back its own changes, so delete it afterwards.

L1 (Junior): Why is a cancelled registration kept instead of deleted?

What the interviewer is testing: Do you see a record as history, and can you name what depends on it?

Flip to check your answerFold answer back

Perfect answer: A registration records that a member held a place, and cancelling changes that fact without erasing it. Keeping the row lets the member see what happened, lets Sam count cancellations and late ones, and lets Chapter 2’s rule hold that history is kept. The count of places uses only active rows, so a kept cancellation costs no place. Registering again makes a new row, so each attempt stays visible, and the database rule allows at most one active row per member and event.

Table 31.5 — Deleting or keeping a cancelled place
Question Deleted Kept as cancelled
Did Raj ever have a place? Unknown Yes, with both times
Late cancellations counted? No Yes, from cancelled_at
Places counted correctly? Yes Yes, active rows only

Behind the scenes:

row 1: cancelled, on time   -> kept, not counted
row 2: cancelled, late      -> kept, not counted
places taken                -> active rows only

Code proof: l1_keep.py registers Raj twice and cancels both, the second time late:

"""Proof: a cancelled place is kept, and lateness read."""
from datetime import timedelta

from allauth.account.models import EmailAddress
from django.db import transaction
from django.utils import timezone

from accounts.models import User
from events.models import Event

with transaction.atomic():
    start = timezone.now() + timedelta(days=7)
    event = Event.objects.create(
        title='Practice clinic', starts_at=start,
        ends_at=start + timedelta(hours=1), timezone='UTC',
        location='Online', capacity=2, status='published',
        registration_closes_at=start,
        cancellation_deadline=start - timedelta(days=2),
    )
    raj = User.objects.create_user('raj@example.net',
                                   display_name='Raj')
    EmailAddress.objects.create(user=raj, email=raj.email,
                                verified=True)
    now = start - timedelta(days=3)
    event.register(raj, now).cancel(now)
    late = start - timedelta(days=1)
    event.register(raj, now).cancel(late)
    rows = event.registrations.filter(member=raj)
    print('rows kept:', rows.count())
    print('active now:', rows.active().count())
    print('late:', [place.is_late() for place in rows])
    print(event.registrations.cancellation_counts())
    transaction.set_rollback(True)
rows kept: 2
active now: 0
late: [False, True]
{'cancelled': 2, 'late': 1}

Common mistakes:

  • Deleting the row on cancel, and losing every count that depends on it.
  • Storing “late” in a field that can disagree with the deadline after an edit.
  • Reusing the old row on re-registration, which hides the earlier cancellation.

Follow-up the interviewer might ask:

  • “When would you delete registrations, and who decides?”
  • “How would you show a member their own history?”

L2 (Mid-Level): Soni registers at exactly the closing time, then a moment earlier on a full event. Predict both answers.

What the interviewer is testing: Can you read a boundary rule precisely, and see which reasons apply together?

Flip to check your answerFold answer back
Five numbered steps. Soni posts Register at exactly the closing time. Closing is exclusive: at that instant the answer is closed. One microsecond earlier she could have registered. On a full event the answer is full, whatever the time. Either way no row is written, and the reason is named.
Figure 31.5 — Soni at the edge.

Perfect answer: At exactly the closing time she is refused with closed, because closing is exclusive: registration is open strictly before it. One microsecond earlier the window is open, so on an event with room she would get a place. On a full event, one microsecond earlier, the answer is full. Neither request writes a row, and each answer names its reason, so the page can say “Registration has closed.” or “This event is full.”

Behind the scenes:

now <  opens   -> not_open
now >= closes  -> closed
taken >= cap   -> full

Code proof: l2_predict.py:

"""Proof: the closing instant, and a full event."""
from datetime import timedelta

from allauth.account.models import EmailAddress
from django.db import transaction
from django.utils import timezone

from accounts.models import User
from events.models import Event

TICK = timedelta(microseconds=1)


def member(name):
    """Create a member whose email address is confirmed."""
    user = User.objects.create_user(f'{name}@example.net',
                                    display_name=name)
    EmailAddress.objects.create(user=user, email=user.email,
                                verified=True)
    return user


with transaction.atomic():
    start = timezone.now() + timedelta(days=7)
    closes = start - timedelta(days=1)
    event = Event.objects.create(
        title='Practice clinic', starts_at=start,
        ends_at=start + timedelta(hours=1), timezone='UTC',
        location='Online', capacity=1, status='published',
        registration_closes_at=closes,
        cancellation_deadline=closes,
    )
    soni = member('soni')
    print('a tick before closing:',
          event.registration_problems(soni, closes - TICK))
    print('at closing:          ',
          event.registration_problems(soni, closes))
    event.register(member('sai'), closes - TICK)
    print('full, a tick before: ',
          event.registration_problems(soni, closes - TICK))
    transaction.set_rollback(True)
a tick before closing: []
at closing:           ['closed']
full, a tick before:  ['full']

Common mistakes:

  • Writing now > closes, which lets a request through at the closing instant.
  • Checking the time in the browser, which the member’s device controls.
  • Reporting only the first reason, so a member fixes one problem and meets the next.

Follow-up the interviewer might ask:

  • “Which clock does Otahque trust, and why?”
  • “How would you show the closing time in the member’s own zone?”

L3 (Senior): register() already checks for an existing place. Why keep the unique constraint, and why translate only one error?

What the interviewer is testing: Can you defend defence in depth, and keep an error handler from hiding faults?

Flip to check your answerFold answer back
Five numbered steps. Goal: one active place per member, always. register() checks first, for a readable answer. The unique rule refuses whatever slips past. Only that rule means already registered. Any other IntegrityError is raised again.
Figure 31.6 — The check and its backstop.

Perfect answer: The check gives members a clear answer in the ordinary case, but it runs before the insert, and two requests from the same member can both pass it before either writes. Only the database sees every insert, so the partial unique index is the rule that cannot be skipped, by a race, a script, or a future view that forgets. When it refuses, register() confirms that the member now holds a place before calling it a repeat; any other IntegrityError is raised again, so a real fault is reported instead of shown as success.

Behind the scenes:

atomic:
  problems? -> ValidationError
  atomic: insert
  IntegrityError:
    place found -> already_registered
    no place    -> raise again

Code proof: l3_backstop.py skips the checks, then breaks the save:

"""Proof: the backstop, and errors it must not hide."""
from datetime import timedelta
from unittest import mock

from allauth.account.models import EmailAddress
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
from django.utils import timezone

from accounts.models import User
from events.models import Event
from registrations.models import Registration

with transaction.atomic():
    start = timezone.now() + timedelta(days=7)
    event = Event.objects.create(
        title='Practice clinic', starts_at=start,
        ends_at=start + timedelta(hours=1), timezone='UTC',
        location='Online', capacity=5, status='published',
        registration_closes_at=start,
        cancellation_deadline=start,
    )
    sai = User.objects.create_user('sai@example.net',
                                   display_name='Sai')
    raj = User.objects.create_user('raj@example.net',
                                   display_name='Raj')
    for person in (sai, raj):
        EmailAddress.objects.create(user=person,
                                    email=person.email,
                                    verified=True)
    now = timezone.now()
    event.registrations.create(member=sai)
    skip = mock.patch.object(Event, 'registration_problems',
                             return_value=[])
    with skip:
        try:
            event.register(sai, now)
        except ValidationError as error:
            print('checks skipped:', error.messages)
    print('active places:', event.places_taken())
    other = IntegrityError('NOT NULL constraint failed')
    with skip, mock.patch.object(Registration, 'save',
                                 side_effect=other):
        try:
            event.register(raj, now)
        except IntegrityError as error:
            print('other error re-raised:', error)
    transaction.set_rollback(True)
checks skipped: ['You already have a place.']
active places: 1
other error re-raised: NOT NULL constraint failed

Common mistakes:

  • Dropping the constraint because “the code already checks”.
  • Catching every IntegrityError as a duplicate.
  • Catching it without an inner atomic(), which leaves the transaction unusable.

Follow-up the interviewer might ask:

  • “Would a ModelForm with fields = ['event'] check the rule?”
  • “How would an API return this refusal?”

L4 (Staff): A registration test passes all day and fails in one evening run. Diagnose it.

What the interviewer is testing: Can you find time-dependent flakiness and remove it by design rather than by retrying?

Flip to check your answerFold answer back
Five numbered steps. A test passes in the morning and fails at night. It compares with the real clock near a boundary. The boundary moved past now during the run. Pass now in: one microsecond before, exactly at. The same answer on every run.
Figure 31.7 — A test that reads the clock.

Perfect answer: The test builds an event whose closing time is relative to the real clock, then checks the rules with the real clock again. If the run is slow, or the times fall near midnight or a clock change, the boundary passes between the two readings and the answer flips. The fix is in the design: the rules take now as an argument, and the test passes fixed instants on each side of the boundary. Freezing the clock with a package also works for Python, but not for the database’s own clock, so passing now is the more complete answer.

Behind the scenes:

setup:  closes = clock() + 1 s
check:  clock() later  -> may be after closes
fixed:  check(closes - 1 microsecond) -> always open

Code proof: l4_clock.py asks the same question twice with the real clock, then once with a fixed instant:

"""Proof: a check against the real clock changes answer."""
import time
from datetime import timedelta

from django.db import transaction
from django.utils import timezone

from events.models import Event

with transaction.atomic():
    soon = timezone.now() + timedelta(seconds=1)
    start = soon + timedelta(days=1)
    event = Event.objects.create(
        title='Practice clinic', starts_at=start,
        ends_at=start + timedelta(hours=1), timezone='UTC',
        location='Online', capacity=5, status='published',
        registration_closes_at=soon,
        cancellation_deadline=soon,
    )
    print('real clock, now:  ', event.open_problems(
        timezone.now()))
    time.sleep(1.2)
    print('real clock, later:', event.open_problems(
        timezone.now()))
    fixed = soon - timedelta(microseconds=1)
    print('fixed instant:    ', event.open_problems(fixed))
    transaction.set_rollback(True)
real clock, now:   []
real clock, later: ['closed']
fixed instant:     []

Common mistakes:

  • Rerunning the suite until it passes and calling the failure “flaky”.
  • Freezing Python’s clock while the query uses the database’s now().
  • Fixing one test instead of making every rule take now.

Follow-up the interviewer might ask:

  • “Where would a fixed now be wrong, and the real clock right?”
  • “How would you test a deadline across a daylight-saving change?”

L5 (Lead): Otahque counts places inside a transaction on SQLite. Is capacity safe? What must Chapter 33 change?

What the interviewer is testing: Can you state what a design proves and what it does not, and plan the step that closes the gap?

Flip to check your answerFold answer back
Five numbered steps. Goal: never more places than capacity. Count, then insert, in one transaction. SQLite: one writer at a time; no row locks. Two overlapping requests: unproved here. Chapter 33 locks the event on PostgreSQL and proves it.
Figure 31.8 — What this chapter proves.

Perfect answer: Not proved. The count and the insert share a transaction, so a failure leaves nothing half-done, but a transaction alone does not stop two requests from both counting one place left and both inserting. SQLite happens to let one writer at a time, which hides the problem in development, and it cannot lock rows, so the fix cannot be shown here either. The unique rule protects against duplicates from one member, not against too many members. On PostgreSQL, Chapter 33 locks the event row with select_for_update() at the top of register(), so a second request waits until the first has committed and then counts again, and proves it with a test that runs two connections at once. Because every caller goes through register(), nothing else changes.

Behind the scenes:

A: count 0 -> room     B: count 0 -> room
A: insert              B: insert
result: 2 places       (Chapter 33: B waits, counts 1)

Code proof: l5_sqlite.py runs both checks before either insert, as two overlapping requests could on PostgreSQL. It is the chapter’s optional lab:

"""Proof: what SQLite cannot show about overlapping requests."""
from datetime import timedelta

from allauth.account.models import EmailAddress
from django.db import connection, transaction
from django.utils import timezone

from accounts.models import User
from events.models import Event

print('database:', connection.vendor)
print('can lock rows:',
      connection.features.has_select_for_update)
with transaction.atomic():
    start = timezone.now() + timedelta(days=7)
    event = Event.objects.create(
        title='Practice clinic', starts_at=start,
        ends_at=start + timedelta(hours=1), timezone='UTC',
        location='Online', capacity=1, status='published',
        registration_closes_at=start,
        cancellation_deadline=start,
    )
    people = []
    for name in ('sai', 'soni'):
        user = User.objects.create_user(
            f'{name}@example.net', display_name=name)
        EmailAddress.objects.create(
            user=user, email=user.email, verified=True)
        people.append(user)
    now = timezone.now()
    # Both checks run before either insert, as two
    # overlapping requests could on PostgreSQL.
    print('checks:', [event.registration_problems(p, now)
                      for p in people])
    for person in people:
        event.registrations.create(member=person)
    print('capacity 1, places taken:', event.places_taken())
    transaction.set_rollback(True)
database: sqlite
can lock rows: False
checks: [[], []]
capacity 1, places taken: 2

Common mistakes:

  • Treating atomic() as a lock.
  • Trusting SQLite’s single writer, which PostgreSQL does not share.
  • Adding select_for_update() here, where SQLite ignores it and a test passes for the wrong reason.

Follow-up the interviewer might ask:

  • “Would a CHECK constraint on capacity work instead?”
  • “How would a waiting list (Chapter 46) change the count?”

Next: Chapter 32, Moving to PostgreSQL, keeps every behaviour of this checkpoint and changes the database under it.

PAGE 006