ContentsClose contents
Pre-release
Chapter 46 · Waitlists, check-in, and registration state transitionsCHAPTER 46

Complete six-part pre-release for review. Seven migrations, three of them written by hand to add a unique reference to existing places. Cancelling now takes the event's lock. Six earlier tests change on purpose (declared in the chapter). Milestone 3’s acceptance trace passes; it counts as reached once the trace has been reviewed.

Milestone reached in this chapter: Event-day operations. Reminders sent in the background, a waitlist that offers released places, and check-in that records each attendance once. All milestones

CHAPTER FORTY-SIX

Waitlists, check-in, and registration state transitions

Stage 5: Growing the application (Chapters 35 to 46)

Prerequisites: Chapters 9 to 45, including the Chapter 45 project with its 569 passing tests, the event lock and register() (Chapter 33), the details page with its questions (Chapters 35 and 38), the audit trail (Chapter 30), deliveries and send_due_reminders (Chapter 44), and the swappable registration panel (Chapter 45)

What you’ll build: a waitlist that members join when an event is full, with their turn shown; automatic promotion of the first member waiting, under the event’s lock, when a place is cancelled or the capacity rises; waitlists that close with registration; a check-in code for every place, shown as a QR picture; a check-in window each organizer chooses; a door page for checking members in by name, and a scan page for their codes; attendance on the attendee list; and the trace that closes Milestone 3

Why This Matters

The clinic is full by Tuesday. Soni would come if a place came up, but Otahque can only tell her “This event is full.” On Thursday, Raj cancels; the place sits empty, because nobody knows it is free, or the first person to look takes it, by luck. On the day, Sam stands at the door with a printed list, ticking names, while two helpers tick the same person twice. Afterwards he cannot say who came, and Chapter 72’s ratings, which only members who came may give, need exactly that fact.

Three things have been tangled together: holding a place, waiting for one, and coming to the event. This chapter keeps them apart. A waitlist records who is waiting, in order; when a place frees, Otahque gives it to the first member waiting, in the same transaction that freed it, under the event’s lock, so it can never go to two people. A check-in records who came, once, and who said so; a mistake can be undone, and the undo is recorded too.

This is also the last chapter of Milestone 3, event-day operations. Its final step traces each of the milestone’s promises to the tests that keep it.

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

  • keep a place, a turn on a waitlist, and attendance as three facts, each with its own states and changes;
  • give a freed place to the first member waiting inside the transaction that freed it, and prove under concurrency that it is given once;
  • add a unique field to a table that already has rows, in three migrations;
  • choose between a stored reference, a hash, and a signature for a code, and say why a code that opens a page is not authority;
  • record an action once even when two people press at the same moment, and keep an undo as history;
  • trace a milestone’s acceptance checks to named tests.

Out of scope: volunteers who check members in (Chapter 70), offers that expire for paid places (not planned), a live count pushed to the organizers’ phones (Chapter 54), attendance reports (Chapter 55), and checking in without a network.

PAGE 001

What You Need to Know

Three facts, not one

New Concept: states and transitions

What problem exists? A member can hold a place, wait for one, cancel, and come or not come. Kept in one field, these turn into combinations nobody planned, such as “cancelled but checked in”.

What did people do before? Added flags one at a time, is_waiting, attended, and handled each combination where it appeared.

What is it? A state is where a record is; a transition is a change from one state to another, with a rule saying when it is allowed and who may make it. Writing them down as a table, states in rows and events across, shows every allowed change, and makes the forbidden ones visible.

Why use it? Each fact gets its own record and its own small set of states, and the rules sit in one method each.

Now let’s use it. Table 46.1 is Otahque’s, and Step 15 records it in the design notes.

Table 46.1 — The three facts and their transitions
From Event To Who
(none) Join, when full and open waiting Member
waiting A place frees, while open promoted Otahque
waiting Leave left Member
waiting Registration ends closed Scheduler
active Cancel cancelled Member
active Check in, inside the window checked in Organizer
checked in Undo, inside the window undone Organizer
undone Check in again checked in Organizer

A place is a Registration, active or cancelled, as since Chapter 31. A turn is a new model, WaitlistEntry: waiting, then promoted, left, or closed, and never deleted. Attendance is another new model, CheckIn, one per place. Figure 46.1 draws them side by side.

Three columns. A place, Registration: active, an arrow labelled cancel to cancelled. A turn, WaitlistEntry: waiting, with three arrows, a place frees to promoted, leave to left, registration ends to closed. Attendance, CheckIn: not yet, check in to checked in, undo to undone, check in again back to checked in. A dashed arrow from promoted to active in the first column, labelled the place it became.
Figure 46.1 — A place, a turn, and attendance.

Promotion inside the lock

Since Chapter 33, register() locks the event’s row, so requests for one event take turns. Cancelling has not needed the lock: of two cancels, only one can change an active row. Promotion changes that. “Free Raj’s place, then give it to Soni” is two changes, and if anything runs between them, a newcomer’s request can take the place first and Soni, who waited longest, loses it. So cancel() now locks the event too, and makes both changes in one transaction. Figure 46.2 shows why that is enough.

Five numbered cards in order. 1, Raj presses Cancel: cancel() locks the event row. 2, his place becomes cancelled. 3, fill_from_waitlist() takes the first member waiting, Soni, and calls register() for her, with every rule. 4, the transaction commits: Raj’s place is free and Soni has it, together. 5, a newcomer who pressed Register meanwhile waited for the lock, counts again, and is told the event is full.
Figure 46.2 — Promotion inside the event’s lock.

The promotion calls register(), the same method a member’s request calls, with source='waitlist'. Every rule therefore holds: the email confirmed, the phone number, the event’s questions. That raises a question the plan review asked: what if a member waiting has not answered a question the organizer added later? Otahque skips them, keeps their turn, emails them once, and gives the place to the next member (N46.9). To keep that rare, joining the waitlist asks the same questions as registering, and keeps the answers on the entry.

Under the Hood: a unique field on a table with rows

Every place needs its own check-in reference, a unique column. Adding a unique column to a table that already has rows is a trap: a migration’s default is worked out once, so every existing row would get the same value, and the unique rule would fail. Django’s documentation gives the way round it, in three migrations: add the column allowing empty values; fill each row with its own value in Python; then make the column unique and required. They are three migrations, not three steps of one, because PostgreSQL will not change a table’s definition in the same transaction that has just updated its rows and still has their constraint checks waiting to run.

A code is a key, not a ticket

At the door, a member shows a QR code; an organizer scans it; Otahque checks them in. What does the code hold? The plan first said “a random token, stored as a hash”, the way passwords are stored. But Otahque has to draw the code every time the member opens it, and a hash cannot be turned back into the code. The question is what the code is for (N46.8).

Table 46.2 — Three ways to keep a check-in code
Way What is stored What it costs
A random reference, stored as it is (Otahque) 22 random characters, unique, on the place Readable in a stolen copy of the database; harmless there, because it only finds a place
A hash of a random code Only the hash The code can be shown once, by email; lost email, no code
A signature of the place's id Nothing Changing SECRET_KEY changes every code; one code cannot be stopped alone

The code opens an address, /check-in/<reference>/, that only the event’s current organizers can use, signed in, and that checks a member in only on a POST. Anyone else who opens it, the member included, is refused, and the refusal is recorded. So the reference is a key to look a place up, not authority: what decides is who is signed in. Stored as it is, it can be drawn every time, and stopped by giving the place a new one. Figure 46.3 shows what it carries.

Two columns. Left, what the code carries: the address otahque.tech/check-in/ and 22 random characters; nothing about the member. Right, what decides: the person is signed in; they are a current organizer of this event; it is a POST, not a link preview; the place is still held; check-in is open now. Under both: Sai opening her own code is refused, and recorded.
Figure 46.3 — What a check-in code carries, and what decides.

New Tool: qrcode

What problem exists? A link must reach an organizer’s phone without anyone typing it.

What did people do before? Printed lists, typed numbers, or a paid ticketing service.

What is it? qrcode is a Python package that draws QR codes. Its SVG output is one <svg> element with a single path and no <style>, so it scales with CSS and obeys the security policy Chapter 59 sets. Version 8.2 is already in Otahque’s lock file, because django-allauth draws two-factor codes with it (Chapter 29); Step 12 declares it directly, since Otahque now imports it itself.

Why use it? Any phone camera reads a QR code, and no service sees Otahque’s data.

Now let’s use it. Step 12 draws each place’s code on a page of its own.

Once, even at the same moment

Two organizers at the door scan Sai’s code a second apart. Both requests check whether she is in; neither finds a record; both write one. The cure is the one Chapter 33 used for places: lock the row first. check_in() locks the place’s row with select_for_update(), so the second request waits, then finds the first one’s record and is told “Already checked in”. There is one CheckIn per place, a one-to-one link, which the database also enforces.

An undo keeps the row and fills in undone_at and undone_by; checking in again clears them. The row holds where the member stands now; the history, every check-in, undo, and refusal, goes into Chapter 30’s audit trail, written in the same transaction (N46.11).

In practice: a waitlist that people trust

Situation. A popular community meetup fills in a day, and a few members always drop out the week before.

Application. A first-come, first-served waitlist that promotes at once, and tells the member by email, fills those places without an organizer watching. Showing each member their turn, “3rd in line”, answers the question they would otherwise send to the organizers.

Consideration. Automatic promotion assumes the member still wants the place. For free events that is usually so, and a member who no longer does cancels, which promotes the next. For paid or scarce places, an offer that expires is the usual design; Otahque records that as the alternative it did not take (D46.1).

When check-in is open

A code scanned a week early should not count as coming. Each event has a check-in window: it opens some time before the start and closes at the end or a little after. The organizer chooses both from fixed lists, 30 minutes to a day before (2 hours unless changed) and at the end or an hour after (the end unless changed). They are stored as durations, so the window moves with the event. Figure 46.4 shows the default.

A timeline. 16:30, check-in opens, 2 hours before the start, the organizer’s choice. 18:30, the event starts. 20:30, the event ends, and check-in closes, unless the organizer chose an hour after. A check-in at 16:29 is refused; at 16:30, allowed; at 20:30, refused.
Figure 46.4 — The check-in window, with the default choices.
PAGE 002

How We Build It

Start from Chapter 45, in the folder containing manage.py, with Otahque on PostgreSQL 18, 569 passing tests, and the work committed (the last commit is “Swap parts of pages with htmx”). One package is declared, qrcode 8.2, which is already in uv.lock, so nothing new is downloaded. Seven migrations are new: four in registrations, three of them written by hand, one in audit, and one in events. The new files are a module that draws codes, four templates (the code page, the door page, its swap answer, and the scan page), nine test modules, and the Milestone 3 trace. The settings, the registrations models, views, and URLs, the events models, views, forms, and emails, the scheduled command, the audit actions, six templates, the stylesheet, two design notes, and six earlier test modules change. The visible result: a full event offers its waitlist and gives a freed place to the first member waiting; each place has a QR code; on the day, organizers check members in by name or by code, once, and the attendee list shows who came. The commands were checked in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.

The Custom Way

Without these models, an organizer runs a waitlist in a spreadsheet: names in the order the emails arrived, and when Raj cancels, an email to the first name, then a wait, then maybe the next. Check-in is ticks on a printed list. Both work for twenty people. They fail at the edges this chapter is about: two cancels in the same minute, two helpers ticking the same name, a newcomer who registers while the organizer is still emailing, and nobody able to say afterwards who came. The Django way puts each fact in a table, each change in one method, and every change that can race under a lock.

The Django Way

Step 1: Check the starting point

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

OK
git status --short
git log --oneline -1
... Swap parts of pages with htmx

Step 2: The waitlist model

In registrations/models.py, the top of the file becomes:

"""Members' places at Otahque's events."""
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import timezone

from events import emails

The entry’s methods queue emails, which Steps 4 and 6 write. In Registration.Source, below IMPORT:

        WAITLIST = 'waitlist', 'From the waitlist'

and at the end of the file:

class WaitlistQuerySet(models.QuerySet):
    """Named questions about waitlist entries."""

    def waiting(self):
        """Entries still waiting, first come first."""
        return self.filter(
            status=WaitlistEntry.Status.WAITING
        ).order_by('joined_at', 'pk')


class WaitlistEntry(models.Model):
    """A member waiting for a place at a full event (46).

    Kept when it ends: given a place, left by the member,
    or closed when registration closed (D46.2).
    """

    class Status(models.TextChoices):
        """Where an entry is."""

        WAITING = 'waiting', 'Waiting'
        PROMOTED = 'promoted', 'Given a place'
        LEFT = 'left', 'Left the waitlist'
        CLOSED = 'closed', 'Closed: no place came up'

    event = models.ForeignKey(
        'events.Event', on_delete=models.PROTECT,
        related_name='waitlist',
    )
    member = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT,
        related_name='waitlist_entries',
    )
    status = models.CharField(max_length=10, choices=Status,
                              default=Status.WAITING)
    joined_at = models.DateTimeField(default=timezone.now)
    ended_at = models.DateTimeField(null=True, blank=True)
    # The event's questions, answered when joining, so a
    # promotion has them (N46.9): {q_<id>: value}.
    answers = models.JSONField(default=dict, blank=True)
    # When a promotion first passed this member over, as the
    # event asked something new; cleared when answered.
    skipped_at = models.DateTimeField(null=True, blank=True)
    place = models.OneToOneField(
        Registration, on_delete=models.PROTECT, null=True,
        blank=True, related_name='waitlist_entry',
    )

    objects = WaitlistQuerySet.as_manager()

    class Meta:
        ordering = ['joined_at', 'pk']
        verbose_name_plural = 'waitlist entries'
        constraints = [
            models.UniqueConstraint(
                fields=['event', 'member'],
                condition=models.Q(status='waiting'),
                name='waitlist_one_waiting',
                violation_error_code='already_waiting',
                violation_error_message=(
                    'This member is already waiting for '
                    'this event.'
                ),
            ),
        ]

    def __str__(self):
        return f'{self.member} waiting for {self.event}'

    def position(self):
        """Return this entry's place in line, from 1."""
        ahead = WaitlistEntry.objects.waiting().filter(
            event_id=self.event_id
        ).filter(
            models.Q(joined_at__lt=self.joined_at)
            | models.Q(joined_at=self.joined_at,
                       pk__lt=self.pk)
        )
        return ahead.count() + 1

    def promote(self, place, now):
        """Record the place this entry became; email once."""
        self.status = self.Status.PROMOTED
        self.place = place
        self.ended_at = now
        self.save(update_fields=['status', 'place',
                                 'ended_at'])
        if place.source == Registration.Source.WAITLIST:
            emails.place_from_waitlist(place)

    def skip(self, now):
        """Note that a promotion passed this member over.

        The member keeps their turn, and is emailed the
        first time only.
        """
        if self.skipped_at is None:
            self.skipped_at = now
            self.save(update_fields=['skipped_at'])
            emails.waitlist_skipped(self)

    def leave(self, now):
        """Leave the waitlist; return True if this did it."""
        changed = WaitlistEntry.objects.filter(
            pk=self.pk, status=self.Status.WAITING,
        ).update(status=self.Status.LEFT, ended_at=now)
        self.refresh_from_db(fields=['status', 'ended_at'])
        return changed == 1

    def close(self, now):
        """End the entry: no place came up. Email the member."""
        self.status = self.Status.CLOSED
        self.ended_at = now
        self.save(update_fields=['status', 'ended_at'])
        emails.waitlist_closed(self)

The queryset method waiting() gives the line in order: who joined first, and for two at the same instant, the lower id. position() counts the entries ahead. waitlist_one_waiting is a partial unique rule, as registration_one_active is for places: one waiting entry per member and event, while left and closed entries stay as history. leave() changes only a waiting row, in one UPDATE, as cancel() did since Chapter 31.

Leaving someone else’s entry, opening someone else’s code, checking in, and undoing are new actions for the audit trail. In audit/models.py, below ANNOUNCE:

        # Chapter 46: the waitlist and check-in.
        LEAVE_WAITLIST = 'leave_waitlist', 'Leave a waitlist'
        VIEW_CODE = 'view_code', 'Open a check-in code'
        CHECK_IN = 'check_in', 'Check a member in'
        UNDO_CHECK_IN = 'undo_check_in', 'Undo a check-in'

Two migrations, then apply them:

uv run python manage.py makemigrations -n waitlist `
  registrations
uv run python manage.py makemigrations -n waitlist_actions audit
uv run python manage.py migrate
uv run python manage.py makemigrations -n waitlist \
  registrations
uv run python manage.py makemigrations -n waitlist_actions audit
uv run python manage.py migrate
Migrations for 'registrations':
  registrations\migrations\0007_waitlist.py
    ~ Alter field source on registration
    + Create model WaitlistEntry
Migrations for 'audit':
  audit\migrations\0006_waitlist_actions.py
    ~ Alter field action on auditevent
Operations to perform:
  Apply all migrations: account, accounts, admin, audit,
    auth, contenttypes, django_tasks_database, events, mfa,
    registrations, sessions, socialaccount
Running migrations:
  Applying audit.0006_waitlist_actions... OK
  Applying registrations.0007_waitlist... OK

Step 3: Joining and leaving

The tests first, in a new file, registrations/tests/test_waitlist.py:

"""Joining and leaving a waitlist (Chapter 46)."""
from django.core.exceptions import ValidationError
from django.test import TestCase, override_settings
from django.utils import timezone

from accounts.models import Profile
from audit.models import AuditEvent
from events.models import Event
from events.tests.test_tasks import QUEUE_ONLY
from registrations.models import RegistrationQuestion as Question
from registrations.models import WaitlistEntry

from .test_registrations import soon, url, verified


def full(**changes):
    """Create a clinic with one place, taken by Raj."""
    event = soon(capacity=1, **changes)
    raj = verified('raj@example.org')
    event.registrations.create(member=raj)
    return event


@override_settings(TASKS=QUEUE_ONLY)
class JoinTests(TestCase):
    """Who may join the waitlist, and when."""

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

    def join(self, member):
        """Press Join the waitlist as member."""
        self.client.force_login(member)
        return self.client.post(url('join_waitlist',
                                    self.event.pk))

    def test_a_full_event_offers_the_waitlist(self):
        self.client.force_login(self.sai)
        page = self.client.get(self.event.get_absolute_url())
        self.assertContains(page, 'This event is full.')
        # Sai owes nothing, so the button joins at once.
        join = url('join_waitlist', self.event.pk)
        self.assertContains(page, f'hx-post="{join}"')

    def test_members_wait_in_the_order_they_joined(self):
        self.join(self.sai)
        response = self.join(self.soni)
        self.assertRedirects(response,
                             self.event.get_absolute_url())
        sai, soni = WaitlistEntry.objects.all()
        self.assertEqual((sai.position(), soni.position()),
                         (1, 2))
        page = self.client.get(self.event.get_absolute_url())
        self.assertContains(page, '2nd in line')

    def test_joining_twice_keeps_one_entry(self):
        self.join(self.sai)
        self.join(self.sai)
        self.assertEqual(WaitlistEntry.objects.count(), 1)
        page = self.client.get(self.event.get_absolute_url())
        self.assertContains(page, 'You are already on the '
                                  'waitlist.')
        self.assertContains(page, '1st in line')

    def test_a_member_with_a_place_cannot_join(self):
        raj = self.event.registrations.get().member
        with self.assertRaises(ValidationError) as caught:
            self.event.join_waitlist(raj, timezone.now())
        self.assertEqual(caught.exception.error_list[0].code,
                         'already_registered')

    def test_an_event_with_places_says_register_instead(self):
        Event.objects.filter(pk=self.event.pk).update(
            capacity=2)
        with self.assertRaises(ValidationError) as caught:
            self.event.join_waitlist(self.sai, timezone.now())
        self.assertEqual(caught.exception.error_list[0].code,
                         'not_full')

    def test_no_joining_after_registration_closes(self):
        later = self.event.registration_closes_at
        with self.assertRaises(ValidationError) as caught:
            self.event.join_waitlist(self.sai, later)
        self.assertEqual(caught.exception.error_list[0].code,
                         'closed')

    def test_questions_are_asked_before_joining(self):
        Question.objects.create(event=self.event, label='Level',
                                required=True)
        response = self.join(self.sai)
        self.assertRedirects(response, url('waitlist_details',
                                           self.event.pk))
        question = self.event.questions.get()
        self.client.post(url('waitlist_details', self.event.pk),
                         {question.key: 'New'})
        entry = WaitlistEntry.objects.get()
        self.assertEqual(entry.answers, {question.key: 'New'})

    def test_leaving_keeps_the_entry_as_left(self):
        self.join(self.sai)
        entry = WaitlistEntry.objects.get()
        self.client.post(url('leave_waitlist', entry.pk))
        entry.refresh_from_db()
        self.assertEqual(entry.status, 'left')

    def test_someone_elses_entry_is_missing_and_recorded(self):
        self.join(self.sai)
        entry = WaitlistEntry.objects.get()
        self.client.force_login(self.soni)
        response = self.client.post(url('leave_waitlist',
                                         entry.pk))
        self.assertEqual(response.status_code, 404)
        self.assertTrue(AuditEvent.objects.filter(
            actor=self.soni, action='leave_waitlist',
            outcome='refused').exists())

    def test_my_registrations_shows_the_turn(self):
        self.join(self.sai)
        page = self.client.get(url('mine'))
        self.assertContains(page, 'Waiting for a place')
        self.assertContains(page, '1st in line')


class ProfileFirstTests(TestCase):
    """A phone number asked for is kept on the profile."""

    def test_the_details_page_saves_the_phone(self):
        event = full(phone_required=True)
        sai = verified('sai@example.org')
        Profile.of(sai)
        self.client.force_login(sai)
        self.client.post(url('waitlist_details', event.pk),
                         {'phone': '98765 43210'})
        self.assertTrue(event.waitlist.waiting().filter(
            member=sai).exists())
uv run python manage.py test registrations.tests.test_waitlist
Found 11 test(s).
Creating test database for alias 'default'...
ERROR: test_a_full_event_offers_the_waitlist
django.urls.exceptions.NoReverseMatch: Reverse for
    'join_waitlist' not found. 'join_waitlist' is not a valid
    view function or pattern name.
ERROR: test_a_member_with_a_place_cannot_join
AttributeError: 'Event' object has no attribute
    'join_waitlist'
... (9 more like these)
Ran 11 tests in ...s

FAILED (errors=11)

The rules go on the event, beside register(). In events/models.py, two new reasons at the end of REASONS:

    'answers_needed': 'This event asks a few questions '
                      'first.',
    # The waitlist (Chapter 46).
    'already_waiting': 'You are already on the waitlist.',
    'not_full': 'Places are left: register instead.',

and above clean():

    def waitlist_problems(self, member, now, answers=None):
        """List, by code, why member cannot join the waitlist.

        An empty list means they may: the event is full,
        registration is open, and the member could take a
        place if one were free (Chapter 46, D46.2).
        """
        if self.place_of(member):
            return ['already_registered']
        waiting = self.waitlist.waiting()
        if waiting.filter(member=member).exists():
            return ['already_waiting']
        problems = self.open_problems(now)
        if 'full' in problems:
            problems.remove('full')
        elif not problems:
            problems.append('not_full')
        if not has_verified_email(member, member.email):
            problems.append('unverified')
        if self.phone_required and not phone_of(member):
            problems.append('phone_missing')
        if self.needs_answers(member, answers):
            problems.append('answers_needed')
        return problems

    def join_waitlist(self, member, now, answers=None):
        """Put member on the waitlist, or raise ValidationError.

        Under the event lock, like register(): a place freed
        a moment ago is offered as a place, not a turn.
        """
        with transaction.atomic():
            event = self.locked()
            problems = event.waitlist_problems(member, now,
                                               answers)
            if problems:
                raise refusal(problems)
            try:
                with transaction.atomic():
                    return event.waitlist.create(
                        member=member, joined_at=now,
                        answers=answers or {},
                    )
            except IntegrityError:
                raise refusal(['already_waiting']) from None

waitlist_problems() turns register()’s rules round: “full” is what makes joining possible, and an event with places left says “register instead”. The rest are the same checks, so a member who joins has done everything a place needs. join_waitlist() runs under the event lock, so a place freed a moment ago is offered as a place, not as a turn.

The event page’s panel learns two states. In events/views.py, registration_panel() begins:

def registration_panel(event, user, now):
    """Return what the event page says about registering.

    Since Chapter 46: a member already waiting sees their
    turn; a full event that is still open offers its
    waitlist instead of saying only "full".
    """
    if not user.is_authenticated:
        codes = event.open_problems(now)
        return {'reasons': [REASONS[c] for c in codes]}
    place = event.place_of(user)
    entry = None if place else event.waitlist.waiting(
    ).filter(member=user).first()
    codes = [] if place or entry else (
        event.registration_problems(user, now))
    can_wait = 'full' in codes and not {
        'not_published', 'not_open', 'closed'} & set(codes)
    asks = {'phone_missing', 'answers_needed'}
    # A full event that offers its waitlist says so itself.
    shown = [c for c in codes if c not in asks
             and not (can_wait and c == 'full')]

and in the dictionary it returns, 'entry': entry and 'can_wait': can_wait follow 'place': place, and 'reasons' becomes [REASONS[c] for c in shown]. The panel shows “3rd in line” with Django’s ordinal filter, from django.contrib.humanize. In config/settings.py, in INSTALLED_APPS, below staticfiles:

    # Chapter 46: the ordinal filter, "3rd in line".
    'django.contrib.humanize',

The views. In registrations/views.py, the imports become:

import logging

from django.contrib import messages
from django.contrib.humanize.templatetags.humanize import ordinal
from django.core.exceptions import ValidationError
from django.http import StreamingHttpResponse
from django.shortcuts import (
    get_object_or_404, redirect, render,
)
from django.urls import reverse
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views import View
from django.views.generic import (
    DetailView, FormView, ListView,
)
from django.views.decorators.http import (
    require_http_methods, require_POST,
)
from django_htmx.http import HttpResponseClientRedirect

from audit.models import AuditEvent, record
from events import emails
from events.models import REASONS, Event
from events.views import deny, page_numbers, registration_panel

from .forms import DetailsForm, MyPlacesForm
from .models import Registration, WaitlistEntry
from .table import columns, csv_lines, extra_cells

MyRegistrationsView.get_context_data() adds, below 'page_numbers':

            # Chapter 46: where this member is waiting.
            'waiting': self.request.user.waitlist_entries
            .waiting().select_related('event'),

In RegistrationDetailsView, show() passes self.joining, which is false on the class:

            {'event': self.event, 'form': form,
             'joining': self.joining},
        )

    # Chapter 46: the same page joins the waitlist.
    joining = False

and at the end of the file:

# Chapter 46: the waitlist.

def join(request, event, answers=None):
    """Put the member on the waitlist, then say so.

    As take_place(): if the event still needs a phone
    number or answers, the member goes to the details page
    first, so a later promotion has everything (N46.9).
    """
    try:
        entry = event.join_waitlist(request.user,
                                    timezone.now(), answers)
    except ValidationError as error:
        codes = [e.code for e in error.error_list]
        if set(codes) <= {'phone_missing', 'answers_needed'}:
            details = reverse('registrations:waitlist_details',
                              args=[event.pk])
            if request.htmx:
                return HttpResponseClientRedirect(details)
            return redirect(details)
        for message in error.messages:
            messages.error(request, message)
    else:
        messages.success(request, 'You are on the waitlist, '
                         f'{ordinal(entry.position())} in line.')
    if request.htmx:
        return swapped_panel(request, event)
    return redirect(event)


@require_POST
def join_waitlist(request, event_id):
    """Join the full event's waitlist."""
    return join(request, event_for(request, event_id))


class WaitlistDetailsView(RegistrationDetailsView):
    """Ask what the event needs, then join its waitlist.

    The same form as for a place. A member already waiting
    changes their answers here, and keeps their turn.
    """

    joining = True

    def post(self, request, event_id):
        """Keep the details; join, or update the answers."""
        form = self.form(request.POST)
        if not form.is_valid():
            return self.show(form)
        form.save_profile()
        answers = form.answers(timezone.now())
        entry = self.event.waitlist.waiting().filter(
            member=request.user).first()
        if entry is None:
            return join(request, self.event, answers)
        entry.answers = answers
        entry.skipped_at = None
        entry.save(update_fields=['answers', 'skipped_at'])
        messages.success(request,
                         'Answers saved. You keep your turn.')
        return redirect(self.event)


@require_POST
def leave_waitlist(request, entry_id):
    """Leave a waitlist; only your own (404, recorded)."""
    entry = get_object_or_404(
        WaitlistEntry.objects.select_related('event'),
        pk=entry_id)
    if entry.member_id != request.user.pk:
        deny(request, Action.LEAVE_WAITLIST, entry, hidden=True)
    if entry.leave(timezone.now()):
        messages.success(request, 'You left the waitlist.')
    else:
        messages.info(request, 'You were no longer waiting.')
    if request.htmx:
        return swapped_panel(request, entry.event)
    return redirect(entry.event)

join() follows take_place() from Chapter 45, line for line: a member who owes details goes to the details page first, as a whole page for htmx, and the panel answers htmx. WaitlistDetailsView is the details page with a different ending, and also where a waiting member answers a question added later, keeping their turn. The addresses, in registrations/urls.py, at the end of the list:

    # Chapter 46: the waitlist, codes, and check-in.
    path('events/<int:event_id>/waitlist/',
         views.join_waitlist, name='join_waitlist'),
    path('events/<int:event_id>/waitlist/details/',
         views.WaitlistDetailsView.as_view(),
         name='waitlist_details'),
    path('waitlist/<int:entry_id>/leave/',
         views.leave_waitlist, name='leave_waitlist'),

Replace registrations/templates/registrations/panel.html with:

{# Chapter 45: htmx swaps this whole section after #}
{# Register or Cancel; swapped is true only then.  #}
{% load humanize %}
<section id="registration-panel" class="registration-panel
                space-y-3 rounded-box border border-base-300
                bg-base-200 p-4" aria-labelledby="register">
  <h2 id="register" class="text-lg font-semibold"
      tabindex="-1" {% if swapped %}data-focus{% endif %}>
    Registration</h2>
  {% for note in notes %}
    <div class="alert alert-{{ note.level_tag }}">
      <span>{{ note }}</span></div>
  {% endfor %}
  {% if place %}
    <p><span class="badge badge-success">You have a
      place</span> Registered
      {{ place.registered_at|date:"j M Y, H:i" }}.</p>
    {% include "registrations/cancel_dialog.html" %}
  {% elif entry %}
    {# Chapter 46: waiting for a place. #}
    <p><span class="badge badge-info turn-badge">
      {{ entry.position|ordinal }} in line</span>
      You are on the waitlist. If a place comes up, it is
      yours, and we email you.</p>
    {% if entry.skipped_at %}
      {% url 'registrations:waitlist_details' event.pk as more %}
      <p class="notice-card">This event now asks something
        you have not answered, so a place went to the next
        person. <a href="{{ more }}">Answer it</a> to keep
        your turn.</p>
    {% endif %}
    {% url 'registrations:leave_waitlist' entry.pk as leave %}
    <form method="post" action="{{ leave }}"
          hx-post="{{ leave }}"
          hx-target="#registration-panel" hx-swap="outerHTML"
          hx-disabled-elt="find button">
      {% csrf_token %}
      <button type="submit" class="btn btn-outline btn-sm">
        {% include "includes/spinner.html" %}
        Leave the waitlist</button>
    </form>
  {% elif can_wait %}
    <p><span class="badge badge-warning">Full</span>
      This event is full. Join the waitlist: if someone
      cancels, the first person waiting gets the place.</p>
    {% if needs_details %}
      {% url 'registrations:waitlist_details' event.pk as more %}
      <a class="btn btn-primary" href="{{ more }}">
        Join the waitlist</a>
    {% else %}
      {% url 'registrations:join_waitlist' event.pk as wait %}
      <form method="post" action="{{ wait }}"
            hx-post="{{ wait }}"
            hx-target="#registration-panel"
            hx-swap="outerHTML"
            hx-disabled-elt="find button">
        {% csrf_token %}
        <button type="submit" class="btn btn-primary">
          {% include "includes/spinner.html" %}
          Join the waitlist</button>
      </form>
    {% endif %}
  {% elif reasons %}
    <div class="alert alert-warning items-start"
         role="status">
      <div>
        <p class="font-semibold">You cannot register now</p>
        <ul class="list-disc pl-5">
          {% for reason in reasons %}
            <li>{{ reason }}</li>
          {% endfor %}
        </ul>
      </div>
    </div>
    {% 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_details %}
    <a class="btn btn-primary"
       href="{% url 'registrations:details' event.pk %}">
      Register</a>
    {% include "registrations/sharing.html" %}
  {% else %}
    {% url 'registrations:register' event.pk as register %}
    <form method="post" action="{{ register }}"
          hx-post="{{ register }}"
          hx-target="#registration-panel" hx-swap="outerHTML"
          hx-disabled-elt="find button">
      {% csrf_token %}
      <button type="submit" class="btn btn-primary">
        {% include "includes/spinner.html" %}
        Register</button>
    </form>
    {% include "registrations/sharing.html" %}
  {% endif %}
  {% if can_see_attendees %}
    <p><a href="{% url 'registrations:attendees' event.pk %}">
      Attendee list</a></p>
  {% endif %}
</section>

In registrations/templates/registrations/details.html, the button says which it does:

    <button type="submit" class="btn btn-primary">
      {% if joining %}Save and join the waitlist{% else %}
      Save and register{% endif %}</button>

and in mine.html, below the heading:

  {% if waiting %}
    {# Chapter 46: events this member is waiting for. #}
    {% load humanize %}
    <h2 class="list-heading">Waiting for a place</h2>
    <ul class="event-cards">
      {% for entry in waiting %}
        <li class="event-card">
          <a href="{{ entry.event.get_absolute_url }}">
            {{ entry.event.title }}</a>
          <span class="badge badge-info turn-badge">
            {{ entry.position|ordinal }} in line</span>
        </li>
      {% endfor %}
    </ul>
  {% endif %}

The badge, in static/otahque/source.css, above .form-actions:

  /* Chapter 46: a turn on the waitlist. */
  .turn-badge {
    font-weight: 600;
  }

My registrations now asks one more question of the database, for the events the member is waiting for, so Chapter 36’s count of its queries changes on purpose. In registrations/tests/test_lists.py:

    def test_a_fixed_number_of_queries(self):
        # Chapter 46: one more, for the events this member
        # is waiting for.
        for page in [1, 2]:
            with self.subTest(page):
                with self.assertNumQueries(8):
npm run build
uv run python manage.py test registrations.tests.test_waitlist
Found 11 test(s).
Creating test database for alias 'default'...
...
Ran 11 tests in ...s

OK

Step 4: Promotion, under the lock

The tests, in a new file, registrations/tests/test_promotion.py:

"""A freed place goes to the first member waiting (46)."""
from django.test import TestCase, override_settings
from django.utils import timezone

from events.models import Delivery
from events.tests.test_tasks import QUEUE_ONLY
from registrations.models import Registration
from registrations.models import RegistrationQuestion as Question
from registrations.models import WaitlistEntry

from .test_waitlist import full
from .test_registrations import url, verified


@override_settings(TASKS=QUEUE_ONLY)
class PromotionTests(TestCase):
    """A freed place goes to the first member waiting."""

    @classmethod
    def setUpTestData(cls):
        cls.event = full()
        cls.raj_place = cls.event.registrations.get()
        cls.sai = verified('sai@example.org')
        cls.soni = verified('soni@example.org')
        now = timezone.now()
        cls.event.join_waitlist(cls.sai, now)
        cls.event.join_waitlist(cls.soni, now)

    def test_a_cancel_gives_the_place_to_the_first(self):
        self.raj_place.cancel(timezone.now())
        place = self.event.place_of(self.sai)
        self.assertEqual(place.source, 'waitlist')
        entry = WaitlistEntry.objects.get(member=self.sai)
        self.assertEqual((entry.status, entry.place),
                         ('promoted', place))
        self.assertIsNone(self.event.place_of(self.soni))
        self.assertEqual(self.event.places_taken(), 1)

    def test_the_promoted_member_is_emailed(self):
        self.raj_place.cancel(timezone.now())
        delivery = Delivery.objects.get(
            key__startswith='promoted')
        self.assertEqual(delivery.member, self.sai)
        self.assertEqual(delivery.subject,
                         'A place came up: Django clinic')

    def test_the_next_one_moves_up(self):
        self.raj_place.cancel(timezone.now())
        soni = WaitlistEntry.objects.get(member=self.soni)
        self.assertEqual(soni.position(), 1)

    def test_a_member_who_owes_an_answer_is_skipped(self):
        Question.objects.create(event=self.event, label='Level',
                                required=True)
        self.raj_place.cancel(timezone.now())
        self.assertIsNone(self.event.place_of(self.sai))
        sai = WaitlistEntry.objects.get(member=self.sai)
        self.assertEqual(sai.status, 'waiting')
        self.assertIsNotNone(sai.skipped_at)
        self.assertTrue(Delivery.objects.filter(
            key=f'skipped:{sai.pk}:{self.sai.pk}').exists())
        # Soni owes the answer too: nobody is promoted, and
        # the place stays free for anyone who registers.
        self.assertEqual(self.event.places_taken(), 0)

    def test_answering_keeps_the_turn(self):
        question = Question.objects.create(
            event=self.event, label='Level', required=True)
        self.raj_place.cancel(timezone.now())
        self.client.force_login(self.sai)
        self.client.post(url('waitlist_details', self.event.pk),
                         {question.key: 'New'})
        sai = WaitlistEntry.objects.get(member=self.sai)
        self.assertEqual(sai.position(), 1)
        self.assertIsNone(sai.skipped_at)

    def test_nobody_is_promoted_once_closed(self):
        closed = self.event.registration_closes_at
        self.raj_place.cancel(closed)
        self.assertEqual(self.event.places_taken(), 0)
        self.assertFalse(WaitlistEntry.objects.filter(
            status='promoted').exists())
uv run python manage.py test registrations.tests.test_promotion
Found 6 test(s).
Creating test database for alias 'default'...
ERROR: test_a_cancel_gives_the_place_to_the_first
AttributeError: 'NoneType' object has no attribute 'source'
ERROR: test_the_promoted_member_is_emailed
events.models.Delivery.DoesNotExist: Delivery matching query
    does not exist.
... (2 more like these)
Ran 6 tests in ...s

FAILED (failures=2, errors=2)

In registrations/models.py, the Django import becomes from django.db import models, transaction, and cancel() becomes:

    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. Since Chapter 46
        it runs under the event's lock and gives the freed
        place to the first waiting member, in the same
        transaction, so it can be refused as busy.
        """
        if now >= self.event.starts_at:
            raise ValidationError(
                'The event has started, so this place can '
                'no longer be cancelled.', code='started',
            )
        with transaction.atomic():
            event = self.event.locked()
            # 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'])
            if changed:
                event.fill_from_waitlist(now)
        return changed == 1

The promotion itself, in events/models.py, above clean():

    def fill_from_waitlist(self, now):
        """Give free places to waiting members; return them.

        Call it on the locked row, inside its transaction:
        cancel() and save_edit() do. First come, first
        served, each through register(), so every rule
        holds. A member who now owes the event an answer is
        skipped and keeps their turn (N46.9); once
        registration has closed, nobody is promoted.
        """
        made = []
        for entry in self.waitlist.waiting().select_related(
                'member'):
            if self.places_taken() >= self.capacity:
                break
            try:
                place = self.register(entry.member, now,
                                      entry.answers,
                                      source='waitlist')
            except ValidationError as error:
                codes = {e.code for e in error.error_list}
                if codes & {'not_published', *WINDOW}:
                    break
                if codes == {'already_registered'}:
                    entry.promote(self.place_of(entry.member),
                                  now)
                else:
                    entry.skip(now)
                continue
            entry.promote(place, now)
            made.append(place)
        return made

It stops when the event is full again, or at the first refusal that means registration itself is over: nobody is promoted after closing. “Already registered” means the member got a place some other way, so the entry is marked as promoted with that place, and nobody is emailed. The two emails, in events/emails.py, above the reminders’ LEFT:

def place_from_waitlist(registration):
    """Queue the email that a waiting member has a place (46)."""
    event = registration.event
    tasks.queue(
        registration.member, event, 'promoted', registration.pk,
        f'A place came up: {event}', [
            f'A place came up at {event}, {when(event)}, at '
            f'{event.location}, and it is yours.',
            'If you cannot come, cancel it on the event page, '
            'so the next person waiting can have it.',
        ], needs='place')


def waitlist_skipped(entry):
    """Queue the email that a waiting member was passed over."""
    event = entry.event
    tasks.queue(
        entry.member, event, 'skipped', entry.pk,
        f'Answer to keep your turn: {event}', [
            f'A place came up at {event}, but the event now '
            'asks something you have not answered, so it went '
            'to the next person waiting.',
            'Answer on the event page to keep your turn.',
        ])

and the module’s first line says Chapters 43, 44, and 46. The promotion email has needs='place': if Sai cancels before the worker sends it, it is skipped (Chapter 44).

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

OK

Now the race this lock is for. In a new file, registrations/tests/test_races.py:

"""Promotion and check-in at the same moment (Chapter 46).

PostgreSQL only, like Chapter 33's RaceTests: each test
commits its rows, so other threads see them.
"""
from unittest import mock

from django.test import TransactionTestCase, skipUnlessDBFeature
from django.utils import timezone

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

from .test_registrations import at_once, soon, verified


@skipUnlessDBFeature('has_select_for_update')
class PromotionRaceTests(TransactionTestCase):
    """Cancels, a promotion, and a new registration at once."""

    def test_two_cancels_and_a_newcomer(self):
        now = timezone.now()
        event = soon(capacity=2)
        raj = event.register(verified('raj@example.org'), now)
        ana = event.register(verified('ana@example.org'), now)
        sai = verified('sai@example.org')
        soni = verified('soni@example.org')
        event.join_waitlist(sai, now)
        event.join_waitlist(soni, now)
        newcomer = verified('new@example.org')

        def cancel(place):
            return lambda: Registration.objects.get(
                pk=place.pk).cancel(now)

        def register():
            fresh = Event.objects.get(pk=event.pk)
            fresh.register(newcomer, now)
            return 'place'

        with mock.patch('events.models.LOCK_TIMEOUT', '30s'):
            outcomes = at_once(cancel(raj), cancel(ana),
                               register)
        # Each freed place went straight to a waiting member,
        # under the lock, so the newcomer always found it full.
        self.assertEqual(outcomes, [True, True, ['full']])
        self.assertEqual(event.places_taken(), 2)
        for member in (sai, soni):
            self.assertEqual(
                event.registrations.active().filter(
                    member=member).count(), 1)

Chapter 33’s test of a cancel that overlaps a request changes on purpose: the cancel used to slip past the lock, and now waits for it. In registrations/tests/test_registrations.py, add import time below import threading, and in RaceTests:

    def test_a_cancel_during_a_request_only_refuses(self):
        raj = verified('raj@example.org')
        rajs = self.event.register(raj, self.now)
        sai = verified('sai@example.org')
        counted_once = threading.Event()
        count = Event.places_taken

        def counted(event):
            taken = count(event)
            counted_once.set()
            # Give Raj's cancel time to reach the lock and
            # wait for it.
            time.sleep(0.5)
            return taken

        def cancel():
            counted_once.wait(5)
            place = Registration.objects.get(pk=rajs.pk)
            return place.cancel(self.now)

        with mock.patch.object(Event, 'places_taken',
                               counted):
            with mock.patch('events.models.LOCK_TIMEOUT', '30s'):
                outcomes = at_once(cancel, self.register(sai))
        # Sai counted Raj's place, so she is told "full".
        # Since Chapter 46 the cancel takes the event lock, so
        # it waits for her request to finish, then frees the
        # place. A refusal, never a place too many (PR-3).
        self.assertEqual(outcomes, [True, ['full']])
        self.assertEqual(self.event.places_taken(), 0)

The outcome is the same as Chapter 33’s: Sai counted Raj’s place, so she is told “full”, and Raj’s place is then free. What changed is the order: the cancel waits.

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

OK
Found 144 test(s).
Creating test database for alias 'default'...
...
Ran 144 tests in ...s

OK

Common Error: promoting after the transaction

Promoting in the view, after cancel() has returned, looks the same in a test with one request. Between the two transactions, though, the place is free and unlocked, and a newcomer’s request can take it. The race test catches it only on PostgreSQL, with threads; SQLite runs one writer at a time. Keep the two changes in one transaction, under one lock.

Step 5: A higher capacity

Places also free when Sam raises the capacity from 20 to 25. save_edit() already holds the event lock (Chapter 33), so it can promote in the same transaction. The test, at the end of PromotionTests, and its import, from config.helpers import as_sent, in_group, above from events.models import Delivery:

    def test_a_higher_capacity_promotes_in_order(self):
        sam = in_group('sam@example.org', 'Organizers')
        self.event.add_organizer(sam)
        self.client.force_login(sam)
        response = self.client.post(
            f'/events/{self.event.pk}/edit/',
            as_sent(self.event, capacity=3), follow=True)
        self.assertContains(response,
                            '2 waiting members given places.')
        self.assertEqual(self.event.places_taken(), 3)
        self.assertEqual(
            Registration.objects.filter(source='waitlist')
            .count(), 2)
uv run python manage.py test registrations.tests.test_promotion
Found 7 test(s).
Creating test database for alias 'default'...
FAIL: test_a_higher_capacity_promotes_in_order
AssertionError: False is not true : Couldn't find '2 waiting
    members given places.' in the following response
Ran 7 tests in ...s

FAILED (failures=1)

In events/views.py, add from django.template.defaultfilters import pluralize below the shortcuts import, and in save_edit(), above the Chapter 43 comment:

        # Chapter 46: places added by a higher capacity go to
        # waiting members, under this same lock (N46.10).
        moved = event.fill_from_waitlist(timezone.now())
        if moved:
            messages.info(request, f'{len(moved)} waiting '
                          f'member{pluralize(len(moved))} '
                          'given places.')
uv run python manage.py test registrations.tests.test_promotion
Found 7 test(s).
Creating test database for alias 'default'...
...
Ran 7 tests in ...s

OK

Step 6: Closing the waitlist

When registration ends, waiting is over. send_due_reminders already runs every ten minutes (Chapter 44), so it closes waitlists too. The tests, in a new file, registrations/tests/test_closing.py:

"""send_due_reminders closes waitlists (Chapter 46)."""
import io
from datetime import timedelta

from django.core.management import call_command
from django.test import TestCase, override_settings
from django.utils import timezone

from events.models import Delivery, Event
from events.tests.test_tasks import QUEUE_ONLY

from .test_waitlist import full
from .test_registrations import verified


@override_settings(TASKS=QUEUE_ONLY)
class ClosingTests(TestCase):
    """send_due_reminders closes waitlists that have ended."""

    @classmethod
    def setUpTestData(cls):
        cls.event = full()
        cls.sai = verified('sai@example.org')
        cls.entry = cls.event.join_waitlist(cls.sai,
                                            timezone.now())

    def run_command(self):
        """Run the scheduled command; return what it said."""
        out = io.StringIO()
        call_command('send_due_reminders', stdout=out)
        return out.getvalue().strip()

    def test_an_open_waitlist_stays_open(self):
        self.assertIn('closed 0 waitlist entries',
                      self.run_command())

    def test_closed_registration_closes_it_and_tells(self):
        Event.objects.filter(pk=self.event.pk).update(
            registration_closes_at=timezone.now()
            - timedelta(minutes=1))
        self.assertIn('closed 1 waitlist entries',
                      self.run_command())
        self.entry.refresh_from_db()
        self.assertEqual(self.entry.status, 'closed')
        self.assertEqual(
            Delivery.objects.get(
                key__startswith='waitlist_closed').subject,
            'No place came up: Django clinic')

    def test_a_cancelled_event_closes_it(self):
        Event.objects.filter(pk=self.event.pk).update(
            status=Event.Status.CANCELLED)
        self.run_command()
        self.entry.refresh_from_db()
        self.assertEqual(self.entry.status, 'closed')
uv run python manage.py test registrations.tests.test_closing
Found 3 test(s).
Creating test database for alias 'default'...
FAIL: test_a_cancelled_event_closes_it
AssertionError: 'waiting' != 'closed'
FAIL: test_an_open_waitlist_stays_open
AssertionError: 'closed 0 waitlist entries' not found in
    'Queued 0 reminders; enqueued 0 stale deliveries again.'
... (1 more like these)
Ran 3 tests in ...s

FAILED (failures=3)

The email, in events/emails.py, above LEFT:

def waitlist_closed(entry):
    """Queue the email that the waitlist ended with no place."""
    event = entry.event
    tasks.queue(
        entry.member, event, 'waitlist_closed', entry.pk,
        f'No place came up: {event}', [
            f'The waitlist for {event} has closed, and no '
            'place came up for you.',
            'Registration has ended or the event was '
            'cancelled. Thank you for waiting.',
        ])

In events/management/commands/send_due_reminders.py, the docstring and imports become:

"""Queue the reminders that are due, and stale deliveries.

Run every ten minutes by the operating system's scheduler
(Chapter 44): Task Scheduler on Windows, cron or a systemd
timer elsewhere. It only queues; db_worker sends. Since
Chapter 46 it also closes waitlists whose registration
has ended.
"""
from datetime import timedelta

from django.core.management.base import BaseCommand
from django.db import transaction
from django.db.models import Q
from django.utils import timezone

from events import emails
from events.models import Event
from events.tasks import requeue_stale
from registrations.models import WaitlistEntry

above the Command class:

def close_waitlists(now):
    """Close entries whose registration has ended; count them.

    Registration ends at its closing time, or at the start
    if none was set; a cancelled event ends it at once.
    Each member is told no place came up (D46.2).
    """
    ended = (
        Q(event__status=Event.Status.CANCELLED)
        | Q(event__registration_closes_at__lte=now)
        | Q(event__registration_closes_at=None,
            event__starts_at__lte=now)
    )
    count = 0
    for entry in WaitlistEntry.objects.waiting().filter(
            ended).select_related('event', 'member'):
        with transaction.atomic():
            entry.close(now)
        count += 1
    return count

and handle() ends:

        """Queue, close, then report the counts."""
        now = timezone.now()
        queued = due_reminders(now)
        again = requeue_stale(now)
        closed = close_waitlists(now)
        self.stdout.write(f'Queued {queued} reminders; '
                          f'enqueued {again} stale deliveries '
                          f'again; closed {closed} waitlist '
                          'entries.')
uv run python manage.py test registrations.tests.test_closing
uv run python manage.py test events.tests.test_reminders
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s

OK
Found 5 test(s).
Creating test database for alias 'default'...
FAIL: test_the_due_reminder_is_queued_once
AssertionError: 'Queu[15 chars] enqueued 0 stale deliveries
    again; closed 0 waitlist entries.' != 'Queu[15 chars]
    enqueued 0 stale deliveries again.'
Ran 5 tests in ...s

FAILED (failures=1)

Chapter 44’s test read the command’s whole report, which now has a third part. In events/tests/test_reminders.py, it changes on purpose:

        # Chapter 46: the command closes waitlists too.
        self.assertEqual(reminders_now(),
                         'Queued 1 reminders; enqueued 0 stale '
                         'deliveries again; closed 0 waitlist '
                         'entries.')
uv run python manage.py test events.tests.test_reminders
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s

OK

Step 7: A reference for every place

In registrations/models.py, the top of the file becomes:

"""Members' places at Otahque's events."""
import secrets

from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models, transaction
from django.urls import reverse
from django.utils import timezone

from events import emails


def new_ref():
    """Return a new check-in reference (Chapter 46).

    16 random bytes, as 22 characters that are safe in an
    address: nobody can guess one or work it out from
    another.
    """
    return secrets.token_urlsafe(16)

In Registration, below source:

    # Chapter 46: what the member's check-in code stands for.
    # A key to look the place up, not a password: only an
    # organizer who has signed in can use it (N46.8).
    checkin_ref = models.CharField(max_length=32, unique=True,
                                   default=new_ref)

and below is_late():

    def checkin_url(self):
        """Return the address the member's QR code holds."""
        return settings.SITE_URL + reverse(
            'registrations:scan', args=[self.checkin_ref])

    def new_checkin_ref(self):
        """Give the place a new reference; the old one stops."""
        self.checkin_ref = new_ref()
        self.save(update_fields=['checkin_ref'])

checkin_url() builds the address from SITE_URL (Chapter 43), so a code made on your laptop points at your laptop, and one made on the server at the server. Now the three migrations from the Under the Hood box, written by hand in registrations/migrations/. The first, 0008_checkin_ref.py:

"""Add checkin_ref, empty for now (Chapter 46, 1 of 3).

A unique field cannot be added in one step to a table
that has rows: its default is worked out once, so every
row would get the same value. Django's documentation
adds it empty, fills it, then makes it unique.
"""
from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('registrations', '0007_waitlist'),
    ]

    operations = [
        migrations.AddField(
            model_name='registration',
            name='checkin_ref',
            field=models.CharField(max_length=32, null=True),
        ),
    ]

The second, 0009_fill_checkin_ref.py, gives each existing place its own value. It uses secrets directly, not new_ref() from the models, because a migration must keep working even if the models change later:

"""Give each place its own reference (Chapter 46, 2 of 3)."""
import secrets

from django.db import migrations


def fill(apps, schema_editor):
    """Give every place that has none its own reference."""
    Registration = apps.get_model('registrations',
                                  'Registration')
    places = Registration.objects.filter(checkin_ref=None)
    for place in places.iterator():
        place.checkin_ref = secrets.token_urlsafe(16)
        place.save(update_fields=['checkin_ref'])


class Migration(migrations.Migration):

    dependencies = [
        ('registrations', '0008_checkin_ref'),
    ]

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

The third, 0010_checkin_ref_unique.py:

"""Make checkin_ref unique and required (Chapter 46, 3 of 3)."""
from django.db import migrations, models

import registrations.models


class Migration(migrations.Migration):

    dependencies = [
        ('registrations', '0009_fill_checkin_ref'),
    ]

    operations = [
        migrations.AlterField(
            model_name='registration',
            name='checkin_ref',
            field=models.CharField(
                default=registrations.models.new_ref,
                max_length=32, unique=True,
            ),
        ),
    ]
uv run python manage.py migrate
Operations to perform:
  Apply all migrations: account, accounts, admin, audit,
    auth, contenttypes, django_tasks_database, events, mfa,
    registrations, sessions, socialaccount
Running migrations:
  Applying registrations.0008_checkin_ref... OK
  Applying registrations.0009_fill_checkin_ref... OK
  Applying registrations.0010_checkin_ref_unique... OK

Your own places, from the earlier chapters, now each have a reference of their own: the second migration ran on your data.

Step 8: The check-in window

The tests, in a new file, events/tests/test_window.py:

"""When check-in is open, chosen per event (Chapter 46)."""
from datetime import timedelta

from django.test import TestCase
from django.utils import timezone

from config.helpers import as_sent, in_group, save_event
from events.models import Event


class WindowTests(TestCase):
    """Two hours before the start to the end, or as chosen."""

    @classmethod
    def setUpTestData(cls):
        cls.event = save_event(
            starts_at=timezone.now() + timedelta(days=7))

    def test_the_window_is_two_hours_before_to_the_end(self):
        opens, closes = self.event.checkin_window()
        self.assertEqual(self.event.starts_at - opens,
                         timedelta(hours=2))
        self.assertEqual(closes, self.event.ends_at)
        self.assertFalse(self.event.is_checkin_open(
            opens - timedelta(seconds=1)))
        self.assertTrue(self.event.is_checkin_open(opens))
        self.assertFalse(self.event.is_checkin_open(closes))

    def test_an_organizer_may_choose_the_window(self):
        Event.objects.filter(pk=self.event.pk).update(
            checkin_opens=timedelta(minutes=30),
            checkin_closes=timedelta(hours=1))
        self.event.refresh_from_db()
        opens, closes = self.event.checkin_window()
        self.assertEqual(self.event.starts_at - opens,
                         timedelta(minutes=30))
        self.assertEqual(closes - self.event.ends_at,
                         timedelta(hours=1))

    def test_the_choice_is_saved(self):
        event = self.event
        sam = in_group('sam@example.org', 'Organizers')
        event.add_organizer(sam)
        self.client.force_login(sam)
        page = self.client.get(f'/events/{event.pk}/edit/')
        self.assertContains(page, '1 day before')
        # The choices are sent as Python writes a timedelta.
        self.client.post(f'/events/{event.pk}/edit/', as_sent(
            event, checkin_opens=str(timedelta(days=1)),
            checkin_closes=str(timedelta(hours=1))))
        event.refresh_from_db()
        self.assertEqual(event.checkin_opens, timedelta(days=1))
        self.assertEqual(event.checkin_closes,
                         timedelta(hours=1))
uv run python manage.py test events.tests.test_window
Found 3 test(s).
Creating test database for alias 'default'...
ERROR: test_an_organizer_may_choose_the_window
django.core.exceptions.FieldDoesNotExist: Event has no field
    named 'checkin_opens'
ERROR: test_the_window_is_two_hours_before_to_the_end
AttributeError: 'Event' object has no attribute
    'checkin_window'
... (1 more like these)
Ran 3 tests in ...s

FAILED (failures=1, errors=2)

In events/models.py, above the announcement limit:

# When check-in opens before the start, and closes after
# the end (Chapter 46); the organizer picks one of each.
CHECKIN_OPENS = [(timedelta(minutes=30), '30 minutes before'),
                 (timedelta(hours=1), '1 hour before'),
                 (timedelta(hours=2), '2 hours before'),
                 (timedelta(hours=4), '4 hours before'),
                 (timedelta(days=1), '1 day before')]
CHECKIN_CLOSES = [(timedelta(0), 'At the end'),
                  (timedelta(hours=1), '1 hour after the end')]

in Event, below cover:

    # Chapter 46: when organizers may check members in.
    checkin_opens = models.DurationField(
        'check-in opens', choices=CHECKIN_OPENS,
        default=timedelta(hours=2),
    )
    checkin_closes = models.DurationField(
        'check-in closes', choices=CHECKIN_CLOSES,
        default=timedelta(0),
    )

and above can_see_attendees():

    def can_check_in(self, user):
        """Return whether user may check members in (46).

        The event's current organizers, as for its other
        pages; volunteers come in Chapter 70 (D46.4).
        """
        return self.has_organizer(user)

    def checkin_window(self):
        """Return when check-in opens, and when it closes."""
        return (self.starts_at - self.checkin_opens,
                self.ends_at + self.checkin_closes)

    def is_checkin_open(self, now):
        """Return whether members may be checked in now."""
        opens, closes = self.checkin_window()
        return opens <= now < closes

The window ends at closes, excluded, like registration’s closing time (Chapter 31). can_check_in() is a method of its own, although today it only asks has_organizer(), because Chapter 70 adds volunteers here. In events/forms.py, EventForm.Meta.fields ends with 'checkin_opens', 'checkin_closes', and in __init__(), below self.shown = {}:

        # Chapter 46: a form that leaves the check-in window
        # out, such as an older test's, keeps what is saved.
        for name in ('checkin_opens', 'checkin_closes'):
            self.fields[name].required = False

When a form leaves a field with a default out altogether, Django’s ModelForm keeps the saved value; making the two fields optional lets older pages and tests that do not send them work as before. The browser always sends one of the choices. At the end of events/templates/events/event_fields.html:

<fieldset class="form-section">
  <legend>Check-in</legend>
  <div class="form-grid">
    {{ form.checkin_opens.as_field_group }}
    {{ form.checkin_closes.as_field_group }}
  </div>
</fieldset>
uv run python manage.py makemigrations -n checkin_window events
uv run python manage.py migrate
Migrations for 'events':
  events\migrations\0014_checkin_window.py
    + Add field checkin_closes to event
    + Add field checkin_opens to event
Operations to perform:
  Apply all migrations: account, accounts, admin, audit,
    auth, contenttypes, django_tasks_database, events, mfa,
    registrations, sessions, socialaccount
Running migrations:
  Applying events.0014_checkin_window... OK
uv run python manage.py test events.tests.test_window
uv run python manage.py test events.tests.test_events
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s

OK
Found 189 test(s).
Creating test database for alias 'default'...
FAIL: test_fields_use_otahque_styles_and_script
AssertionError: 17 != 15 : Found 17 instances of
    'class="fieldset"' (expected 15) in the following
    response
Ran 189 tests in ...s

FAILED (failures=1)

Chapter 44 counted the edit page’s fields; two more fieldsets and two more selects are on purpose. In events/tests/test_events.py:

        # Chapter 44: the reminders field makes 15; Chapter
        # 46's check-in window makes 17, with two selects.
        for text, count in (('class="fieldset"', 17),
                            ('class="input w-full"', 8),
                            ('class="textarea w-full"', 1),
                            ('class="select w-full"', 3)):
uv run python manage.py test events.tests.test_events
Found 189 test(s).
Creating test database for alias 'default'...
...
Ran 189 tests in ...s

OK

Step 9: The CheckIn record

The tests, in a new file, registrations/tests/test_checkin.py:

"""Registration.check_in() and CheckIn.undo() (Chapter 46)."""
from datetime import timedelta

from django.core.exceptions import ValidationError
from django.test import TestCase
from django.utils import timezone

from audit.models import AuditEvent
from config.helpers import in_group
from registrations.models import CheckIn, Registration

from .test_registrations import soon, verified


def tonight(**changes):
    """Create a clinic starting in an hour: check-in is open."""
    starts = timezone.now() + timedelta(hours=1)
    return soon(**{
        'starts_at': starts,
        'ends_at': starts + timedelta(hours=2),
        'registration_closes_at': starts,
        'cancellation_deadline': starts,
    } | changes)


class CheckInRuleTests(TestCase):
    """Registration.check_in() and CheckIn.undo()."""

    @classmethod
    def setUpTestData(cls):
        cls.event = tonight()
        cls.sam = in_group('sam@example.org', 'Organizers')
        cls.event.add_organizer(cls.sam)
        cls.sai = verified('sai@example.org')
        cls.place = cls.event.register(cls.sai, timezone.now())

    def check_in(self, at=None):
        """Check Sai in, as Sam, by name."""
        return self.place.check_in(self.sam, 'name',
                                   at or timezone.now())

    def test_a_check_in_is_kept_and_recorded(self):
        checkin = self.check_in()
        self.assertEqual(checkin.checked_in_by, self.sam)
        self.assertTrue(AuditEvent.objects.filter(
            action='check_in', target_id=self.place.pk,
            outcome='allowed').exists())

    def test_twice_is_refused(self):
        self.check_in()
        with self.assertRaises(ValidationError) as caught:
            self.check_in()
        self.assertEqual(caught.exception.code,
                         'already_checked_in')

    def test_undo_then_again_one_row_three_records(self):
        self.check_in().undo(self.sam, timezone.now())
        self.check_in()
        self.assertEqual(CheckIn.objects.count(), 1)
        self.assertTrue(CheckIn.objects.get().is_current())
        actions = AuditEvent.objects.filter(
            target_id=self.place.pk,
            action__in=['check_in', 'undo_check_in'],
        ).order_by('pk').values_list('action', flat=True)
        self.assertEqual(list(actions), [
            'check_in', 'undo_check_in', 'check_in'])

    def test_outside_the_window_is_refused(self):
        late = self.event.ends_at
        with self.assertRaises(ValidationError) as caught:
            self.check_in(at=late)
        self.assertEqual(caught.exception.code,
                         'checkin_closed')

    def test_a_cancelled_place_is_refused(self):
        Registration.objects.filter(pk=self.place.pk).update(
            status='cancelled', cancelled_at=timezone.now())
        with self.assertRaises(ValidationError) as caught:
            self.check_in()
        self.assertEqual(caught.exception.code, 'not_held')

In registrations/models.py, the top of the file becomes:

"""Members' places at Otahque's events."""
import secrets

from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models, transaction
from django.urls import reverse
from django.utils import timezone

from audit.models import AuditEvent, record
from events import emails

Action = AuditEvent.Action


def new_ref():
    """Return a new check-in reference (Chapter 46).

    16 random bytes, as 22 characters that are safe in an
    address: nobody can guess one or work it out from
    another.
    """
    return secrets.token_urlsafe(16)

At the end of Registration, below new_checkin_ref():

    def can_check_in(self, now):
        """Raise ValidationError if check-in is not possible."""
        if self.status != self.Status.ACTIVE:
            raise ValidationError(
                'This place is no longer held.',
                code='not_held')
        if not self.event.is_checkin_open(now):
            raise ValidationError(
                'Check-in is not open for this event now.',
                code='checkin_closed')

    def check_in(self, by, method, now):
        """Record that the member came; return the CheckIn.

        The place's row is locked first, so two organizers
        who scan one code at once take turns, and the second
        is told it is done. Raises ValidationError if the
        place is not held, check-in is not open, or the
        member is checked in already. Recorded (N46.11).
        """
        with transaction.atomic():
            place = Registration.objects.select_for_update(
                of=('self',),
            ).select_related('event').get(pk=self.pk)
            place.can_check_in(now)
            checkin = CheckIn.objects.filter(
                registration=place).first()
            if checkin is not None and checkin.is_current():
                raise ValidationError(
                    'Already checked in.',
                    code='already_checked_in')
            if checkin is None:
                checkin = CheckIn(registration=place)
            checkin.checked_in_at = now
            checkin.checked_in_by = by
            checkin.method = method
            checkin.undone_at = checkin.undone_by = None
            checkin.save()
            record(by, Action.CHECK_IN, place, method=method)
        return checkin

and at the end of the file:

class CheckIn(models.Model):
    """That a member came to the event, and who said so (46).

    One per place. An undo is recorded on the row, and a
    later check-in replaces it; every check-in and undo is
    also an AuditEvent, so no step is lost (N46.11).
    """

    class Method(models.TextChoices):
        """How the organizer found the place."""

        CODE = 'code', 'Scanned code'
        NAME = 'name', 'Found by name'

    registration = models.OneToOneField(
        Registration, on_delete=models.PROTECT,
        related_name='checkin',
    )
    checked_in_at = models.DateTimeField()
    checked_in_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT,
        related_name='+',
    )
    method = models.CharField(max_length=10, choices=Method)
    undone_at = models.DateTimeField(null=True, blank=True)
    undone_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT,
        null=True, blank=True, related_name='+',
    )

    def __str__(self):
        return f'Check-in of {self.registration}'

    def is_current(self):
        """Return whether the member counts as checked in."""
        return self.undone_at is None

    def undo(self, by, now):
        """Undo a mistaken check-in; the row stays, recorded."""
        with transaction.atomic():
            checkin = CheckIn.objects.select_for_update(
                of=('self',),
            ).select_related('registration__event').get(
                pk=self.pk)
            checkin.registration.can_check_in(now)
            if not checkin.is_current():
                raise ValidationError(
                    'This check-in was already undone.',
                    code='already_undone')
            checkin.undone_at = now
            checkin.undone_by = by
            checkin.save(update_fields=['undone_at',
                                        'undone_by'])
            record(by, Action.UNDO_CHECK_IN,
                   checkin.registration)
        return checkin

select_for_update(of=('self',)) locks only the place’s row, not the event it reads with it, so the door does not hold up registration. The check-in and its audit row commit together; a refused check-in rolls back and leaves nothing.

uv run python manage.py makemigrations -n checkin registrations
uv run python manage.py migrate
Migrations for 'registrations':
  registrations\migrations\0011_checkin.py
    + Create model CheckIn
Operations to perform:
  Apply all migrations: account, accounts, admin, audit,
    auth, contenttypes, django_tasks_database, events, mfa,
    registrations, sessions, socialaccount
Running migrations:
  Applying registrations.0011_checkin... OK
uv run python manage.py test registrations.tests.test_checkin
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s

OK

Step 10: The door page

Sam opens the door page on his phone. In registrations/models.py, in RegistrationQuerySet, above cancellation_counts():

    def attendance(self):
        """Count places held, and how many came (Chapter 46)."""
        came = models.Q(checkin__isnull=False,
                        checkin__undone_at=None)
        return self.active().aggregate(
            held=models.Count('pk'),
            came=models.Count('pk', filter=came),
        )

In registrations/views.py, add from django.utils.cache import patch_vary_headers below the timezone import, make the models import from .models import CheckIn, Registration, WaitlistEntry, and at the end of the file:

def door_event(request, event_id):
    """Return the event if this member may check people in.

    Hidden: 404; visible but not theirs: 403. Both are
    recorded as refused check-in attempts.
    """
    event = get_object_or_404(Event, pk=event_id)
    if not event.is_visible_to(request.user):
        deny(request, Action.CHECK_IN, event, hidden=True)
    if not event.can_check_in(request.user):
        deny(request, Action.CHECK_IN, event)
    return event


class DoorView(ListView):
    """The check-in page: find a member, check them in.

    Sized for a phone at the door. Searching by name swaps
    the list with htmx; the count stays on top.
    """

    template_name = 'registrations/door.html'
    context_object_name = 'places'

    def get(self, request, *args, **kwargs):
        """Refuse anyone who may not check members in."""
        self.event = door_event(request, kwargs['event_id'])
        self.query = request.GET.get('q', '').strip()
        response = super().get(request, *args, **kwargs)
        patch_vary_headers(response, ['HX-Request'])
        return response

    def get_template_names(self):
        """Return the list alone when htmx asks for it."""
        htmx = self.request.htmx
        if (htmx and htmx.target == 'door-list'
                and not htmx.history_restore_request):
            return [f'{self.template_name}#door-list']
        return super().get_template_names()

    def get_queryset(self):
        """Places held now, by name; matching the search."""
        places = self.event.registrations.active()
        places = places.select_related(
            'member', 'checkin').order_by('member__display_name')
        if self.query:
            places = places.filter(
                member__display_name__icontains=self.query)
        return places

    def get_context_data(self, **kwargs):
        """Add the event, the search, the window, and counts."""
        now = timezone.now()
        return super().get_context_data(**kwargs) | {
            'event': self.event,
            'query': self.query,
            'open': self.event.is_checkin_open(now),
            'window': self.event.checkin_window(),
            'counts': self.event.registrations.attendance(),
        }


def door_answer(request, event, place):
    """Answer a check-in or undo: the row for htmx, else go.

    For htmx, the changed row, the count out of band, and
    the message for the live region.
    """
    if not request.htmx:
        return redirect('registrations:door', event.pk)
    place = Registration.objects.select_related(
        'member', 'checkin').get(pk=place.pk)
    return render(request, 'registrations/door_swap.html', {
        'event': event, 'place': place,
        'open': event.is_checkin_open(timezone.now()),
        'counts': event.registrations.attendance(),
        'notes': list(messages.get_messages(request)),
    })


def refuse_check_in(request, place, error):
    """Show why a check-in or undo was refused; record it."""
    record(request.user, Action.CHECK_IN, place,
           AuditEvent.Outcome.REFUSED,
           reason=error.error_list[0].code)
    messages.error(request, error.messages[0])


def door_place(request, registration_id):
    """Return the place and its event, for the door's buttons."""
    place = get_object_or_404(
        Registration.objects.select_related('member'),
        pk=registration_id)
    return place, door_event(request, place.event_id)


@require_POST
def check_in(request, registration_id):
    """Check a member in, found by name on the door page."""
    place, event = door_place(request, registration_id)
    try:
        place.check_in(request.user, CheckIn.Method.NAME,
                       timezone.now())
    except ValidationError as error:
        refuse_check_in(request, place, error)
    else:
        messages.success(request, f'{place.member.display_name}'
                         ' is checked in.')
    return door_answer(request, event, place)


@require_POST
def undo_check_in(request, registration_id):
    """Undo a mistaken check-in; the record stays."""
    place, event = door_place(request, registration_id)
    checkin = get_object_or_404(CheckIn, registration=place)
    try:
        checkin.undo(request.user, timezone.now())
    except ValidationError as error:
        refuse_check_in(request, place, error)
    else:
        messages.success(request, 'Check-in undone for '
                         f'{place.member.display_name}.')
    return door_answer(request, event, place)

Chapter 45’s patterns again: the list is a partial, chosen when htmx targets it; the buttons answer htmx with the changed row, the count out of band, and words for the live region. Every refusal is recorded with its reason. The addresses, at the end of registrations/urls.py:

    path('events/<int:event_id>/check-in/',
         views.DoorView.as_view(), name='door'),
    path('registrations/<int:registration_id>/check-in/',
         views.check_in, name='checkin'),
    path('registrations/<int:registration_id>/check-in/undo/',
         views.undo_check_in, name='undo_checkin'),

The page, a new file, registrations/templates/registrations/door.html:

{% extends "base.html" %}

{% block title %}Check-in: {{ event.title }} |
  Otahque{% endblock %}

{% block content %}
  <div class="door">
    <h1>Check-in: {{ event.title }}</h1>
    {% partialdef door-count inline %}
    <p id="door-count" class="door-count" role="status"
       {% if swapped %}hx-swap-oob="true"{% endif %}>
      <strong>{{ counts.came }} of {{ counts.held }}</strong>
      checked in</p>
    {% endpartialdef %}
    <div id="door-error"></div>
    {% if not open %}
      <p class="notice-card">Check-in is open from
        {{ window.0|date:"j M, H:i" }} until
        {{ window.1|date:"j M, H:i" }}.</p>
    {% endif %}
    {# Chapter 46: the list follows the search as you #}
    {# type; without JavaScript, press Search.         #}
    {% url 'registrations:door' event.pk as door %}
    <form method="get" class="door-search" role="search"
          hx-get="{{ door }}" hx-target="#door-list"
          hx-swap="outerHTML" hx-push-url="true"
          hx-trigger="input changed delay:300ms, submit">
      <label for="door-q" class="sr-only">Find by name</label>
      <input id="door-q" type="search" name="q"
             value="{{ query }}" placeholder="Find by name"
             class="input input-lg w-full" autocomplete="off">
      <button type="submit" class="btn btn-lg">Search</button>
    </form>
    {% partialdef door-list inline %}
    <ul id="door-list" class="door-list">
      {% for place in places %}
        {% partialdef door-row inline %}
        <li id="place-{{ place.pk }}" class="door-row">
          {% url 'registrations:checkin' place.pk as go %}
          {% url 'registrations:undo_checkin' place.pk as undo %}
          {% with came=place.checkin.is_current %}
          <span class="door-name">
            {{ place.member.display_name }}</span>
          {% if came %}
            <span class="badge badge-success">Checked in
              {{ place.checkin.checked_in_at|date:"H:i" }}
            </span>
          {% else %}
            <span class="badge">Not yet</span>
          {% endif %}
          {% if open and came %}
            <form method="post" action="{{ undo }}"
                  hx-post="{{ undo }}"
                  hx-target="#place-{{ place.pk }}"
                  hx-swap="outerHTML">
              {% csrf_token %}
              <button type="submit" class="btn btn-ghost">
                Undo</button>
            </form>
          {% elif open %}
            <form method="post" action="{{ go }}"
                  hx-post="{{ go }}"
                  hx-target="#place-{{ place.pk }}"
                  hx-swap="outerHTML"
                  hx-disabled-elt="find button">
              {% csrf_token %}
              <button type="submit"
                      class="btn btn-primary btn-lg">
                {% include "includes/spinner.html" %}
                Check in</button>
            </form>
          {% endif %}
          {% endwith %}
        </li>
        {% endpartialdef %}
      {% empty %}
        <li class="door-row">
          {% if query %}Nobody with a place matches
            "{{ query }}".{% else %}Nobody has a place
            yet.{% endif %}</li>
      {% endfor %}
    </ul>
    {% endpartialdef %}
    <p><a href="{{ event.get_absolute_url }}">Back to the
      event</a></p>
  </div>
{% endblock %}

hx-trigger="input changed delay:300ms, submit" searches as Sam types, waiting until he pauses; without JavaScript, the Search button loads the page. The answer to a button, a new file, registrations/templates/registrations/door_swap.html:

{# What htmx gets after Check in or Undo (Chapter 46): #}
{# the row, the count out of band, and the words for   #}
{# the live region.                                     #}
{% include "registrations/door.html#door-row" %}
{% with swapped=True %}
  {% include "registrations/door.html#door-count" %}
{% endwith %}
<p id="live" hx-swap-oob="innerHTML">
  {% for note in notes %}{{ note }} {% endfor %}</p>
{% for note in notes %}
  {% if note.level_tag == 'error' %}
    <div id="door-error" hx-swap-oob="true"
         class="alert alert-error">{{ note }}</div>
  {% endif %}
{% endfor %}

A link for the organizers, in events/templates/events/detail.html, above the draft’s Delete link:

          {% if event.status == 'published' %}
            <a href="{% url 'registrations:door' event.pk %}">
              Check-in</a>
          {% endif %}

The page is sized for a phone held in one hand. In static/otahque/source.css, above .form-actions:

  /* Chapter 46: the door page, sized for a phone held in
     one hand; the count stays on top. */
  .door {
    display: grid;
    gap: 1rem;
    max-width: 40rem;
  }
  .door-count {
    position: sticky;
    top: 0;
    z-index: 1;
    padding: 0.75rem 1rem;
    border-radius: var(--radius-box);
    background-color: var(--color-neutral);
    color: var(--color-neutral-content);
    font-size: 1.25rem;
  }
  .door-search {
    display: flex;
    gap: 0.5rem;
  }
  .door-list {
    display: grid;
    gap: 0.5rem;
  }
  .door-row {
    display: grid;
    grid-template-columns: 1fr auto;
    align-items: center;
    gap: 0.5rem 1rem;
    padding: 0.75rem 1rem;
    border: 1px solid var(--color-base-300);
    border-radius: var(--radius-box);
    background-color: var(--color-base-100);
  }
  .door-name {
    font-size: 1.125rem;
    font-weight: 600;
  }
  .door-row form {
    grid-column: 1 / -1;
  }
  .door-row .btn-lg {
    width: 100%;
  }

The tests, in a new file, registrations/tests/test_door.py:

"""The check-in page, for the event's organizers (46)."""
from django.test import TestCase
from django.utils import timezone

from audit.models import AuditEvent
from config.helpers import in_group
from registrations.models import CheckIn

from .test_checkin import tonight
from .test_registrations import url, verified

HTMX = {'HX-Request': 'true'}


class DoorTests(TestCase):
    """The check-in page, for the event's organizers."""

    @classmethod
    def setUpTestData(cls):
        cls.event = tonight(capacity=3)
        cls.sam = in_group('sam@example.org', 'Organizers')
        cls.event.add_organizer(cls.sam)
        now = timezone.now()
        cls.sai = cls.event.register(
            verified('sai@example.org'), now)
        cls.raj = cls.event.register(
            verified('raj@example.org'), now)
        cls.door = url('door', cls.event.pk)

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

    def test_the_page_counts_and_lists_by_name(self):
        page = self.client.get(self.door)
        self.assertContains(page, '<strong>0 of 2</strong>')
        self.assertContains(page, 'Raj')
        self.assertContains(page, 'Check in')

    def test_a_search_narrows_the_list(self):
        part = self.client.get(self.door, {'q': 'sa'}, headers={
            'HX-Request': 'true', 'HX-Target': 'door-list'})
        self.assertNotContains(part, '<html')
        self.assertContains(part, 'Sai')
        self.assertNotContains(part, 'Raj')

    def test_check_in_by_name_with_htmx_swaps_the_row(self):
        response = self.client.post(url('checkin', self.sai.pk),
                                    headers=HTMX)
        row = f'id="place-{self.sai.pk}"'
        self.assertContains(response, row)
        self.assertContains(response, 'Checked in')
        self.assertContains(response, '<strong>1 of 2</strong>')
        self.assertEqual(CheckIn.objects.get().method, 'name')

    def test_undo_without_htmx_goes_back_to_the_door(self):
        self.client.post(url('checkin', self.sai.pk))
        response = self.client.post(url('undo_checkin',
                                         self.sai.pk))
        self.assertRedirects(response, self.door)
        self.assertFalse(CheckIn.objects.get().is_current())

    def test_another_organizer_is_refused_and_recorded(self):
        raj = in_group('raj2@example.org', 'Organizers')
        self.client.force_login(raj)
        for response in (self.client.get(self.door),
                         self.client.post(url('checkin',
                                              self.sai.pk))):
            self.assertEqual(response.status_code, 403)
        refused = AuditEvent.objects.filter(
            actor=raj, action='check_in', outcome='refused')
        self.assertEqual(refused.count(), 2)
        self.assertFalse(CheckIn.objects.exists())

    def test_the_administrator_is_refused(self):
        admin = in_group('admin@example.org', 'Administrators',
                         is_staff=True)
        self.client.force_login(admin)
        page = self.client.get(self.door)
        self.assertEqual(page.status_code, 403)

    def test_a_refusal_is_recorded_with_its_reason(self):
        self.client.post(url('checkin', self.sai.pk))
        self.client.post(url('checkin', self.sai.pk))
        refused = AuditEvent.objects.get(outcome='refused')
        self.assertEqual(refused.detail,
                         {'reason': 'already_checked_in'})
npm run build
uv run python manage.py test registrations.tests.test_door
Found 7 test(s).
Creating test database for alias 'default'...
...
Ran 7 tests in ...s

OK

Step 11: The scan

The address in the code opens a page that shows whose code it is and a button. In registrations/views.py, at the end:

class ScanView(DetailView):
    """Where an organizer lands after scanning a code (46).

    GET only shows whose code it is; POST checks them in,
    so a link preview or the member's own phone changes
    nothing (B8). Anyone but the event's organizers gets
    403, recorded; an unknown code, 404.
    """

    template_name = 'registrations/scan.html'
    http_method_names = ['get', 'post']
    context_object_name = 'place'
    slug_field = 'checkin_ref'
    slug_url_kwarg = 'ref'
    queryset = Registration.objects.select_related(
        'event', 'member', 'checkin')

    def get_object(self, queryset=None):
        """Return the place, if this member may check it in."""
        place = super().get_object(queryset)
        if not place.event.can_check_in(self.request.user):
            deny(self.request, Action.CHECK_IN, place)
        return place

    def get_context_data(self, **kwargs):
        """Add the event and whether check-in is open."""
        event = self.object.event
        return super().get_context_data(**kwargs) | {
            'event': event,
            'open': event.is_checkin_open(timezone.now()),
        }

    def post(self, request, *args, **kwargs):
        """Check the member in, then go back to the door."""
        place = self.get_object()
        try:
            place.check_in(request.user, CheckIn.Method.CODE,
                           timezone.now())
        except ValidationError as error:
            refuse_check_in(request, place, error)
        else:
            name = place.member.display_name
            messages.success(request, f'{name} is checked in.')
        return redirect('registrations:door', place.event_id)

DetailView finds the place by checkin_ref through slug_field, so an unknown code is 404 before anything else. The address, at the end of registrations/urls.py:

    path('check-in/<str:ref>/', views.ScanView.as_view(),
         name='scan'),

The page, a new file, registrations/templates/registrations/scan.html:

{% extends "base.html" %}

{% block title %}Check in {{ place.member.display_name }} |
  Otahque{% endblock %}

{% block content %}
  <div class="door">
    <h1>{{ place.member.display_name }}</h1>
    <p>{{ event.title }},
      {% include "events/when.html" %}</p>
    {% if place.status == 'cancelled' %}
      <p class="alert alert-error">This place is cancelled.
        Do not check this person in.</p>
    {% elif place.checkin and place.checkin.is_current %}
      <p><span class="badge badge-success">Checked in
        {{ place.checkin.checked_in_at|date:"H:i" }}</span>
        Already checked in.</p>
    {% elif not open %}
      <p class="notice-card">Check-in is not open for this
        event now.</p>
    {% else %}
      {# Only this POST checks in: opening the link, or a #}
      {# preview of it, changes nothing (B8).             #}
      <form method="post">
        {% csrf_token %}
        <button type="submit" class="btn btn-primary btn-lg">
          Check in {{ place.member.display_name }}</button>
      </form>
    {% endif %}
    <p><a href="{% url 'registrations:door' event.pk %}">
      Back to check-in</a></p>
  </div>
{% endblock %}

The tests, in a new file, registrations/tests/test_scan.py:

"""The address in the QR code: look, then confirm (46)."""
from django.test import TestCase
from django.utils import timezone

from audit.models import AuditEvent
from config.helpers import in_group
from registrations.models import CheckIn

from .test_checkin import tonight
from .test_registrations import url, verified


class ScanTests(TestCase):
    """The address in the QR code: look, then confirm."""

    @classmethod
    def setUpTestData(cls):
        cls.event = tonight()
        cls.sam = in_group('sam@example.org', 'Organizers')
        cls.event.add_organizer(cls.sam)
        cls.sai = verified('sai@example.org')
        cls.place = cls.event.register(cls.sai, timezone.now())
        cls.scan = url('scan', cls.place.checkin_ref)

    def test_opening_the_link_changes_nothing(self):
        self.client.force_login(self.sam)
        page = self.client.get(self.scan)
        self.assertContains(page, 'Check in Sai')
        self.assertFalse(CheckIn.objects.exists())

    def test_confirming_checks_in_by_code(self):
        self.client.force_login(self.sam)
        response = self.client.post(self.scan)
        self.assertRedirects(response,
                             url('door', self.event.pk))
        self.assertEqual(CheckIn.objects.get().method, 'code')

    def test_the_member_cannot_check_themselves_in(self):
        self.client.force_login(self.sai)
        for response in (self.client.get(self.scan),
                         self.client.post(self.scan)):
            self.assertEqual(response.status_code, 403)
        self.assertFalse(CheckIn.objects.exists())
        self.assertTrue(AuditEvent.objects.filter(
            actor=self.sai, action='check_in',
            outcome='refused').exists())

    def test_an_unknown_code_is_missing(self):
        self.client.force_login(self.sam)
        page = self.client.get(url('scan', 'not-a-real-code'))
        self.assertEqual(page.status_code, 404)

    def test_a_cancelled_place_says_so_and_is_refused(self):
        self.place.cancel(timezone.now())
        self.client.force_login(self.sam)
        page = self.client.get(self.scan)
        self.assertContains(page, 'This place is cancelled.')
        self.client.post(self.scan)
        self.assertFalse(CheckIn.objects.exists())

    def test_a_replaced_code_is_missing(self):
        old = self.place.checkin_ref
        self.place.new_checkin_ref()
        self.client.force_login(self.sam)
        page = self.client.get(url('scan', old))
        self.assertEqual(page.status_code, 404)
uv run python manage.py test registrations.tests.test_scan
uv run python manage.py test config.tests.test_public
Found 6 test(s).
Creating test database for alias 'default'...
...
Ran 6 tests in ...s

OK
Found 3 test(s).
Creating test database for alias 'default'...
ERROR: test_a_visitor_is_sent_to_sign_in_elsewhere
django.urls.exceptions.NoReverseMatch: Reverse for 'scan'
    with no arguments not found. 1 pattern(s) tried:
    ['check\\-in/(?P<ref>[^/]+)/\\Z']
Ran 3 tests in ...s

FAILED (errors=1)

Chapter 39’s test visits every page signed out, filling each <int:> in its route with 1; the scan’s route has a <str:>. The test changes on purpose, to fill each kind. In config/tests/test_public.py, add import re above from importlib import import_module, and:

            # A number for each <int:>, a word for <str:>
            # (Chapter 46's check-in codes).
            args = [1 if kind == 'int' else 'x' for kind
                    in re.findall(r'<(\w+):', route)]
uv run python manage.py test config.tests.test_public
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s

OK

Common Error: a GET that changes something

If opening the scan address checked the member in, a phone’s link preview, a chat app fetching the link to show a card, or the member opening their own code would all check them in. Pages that change data answer POST; the GET only shows what will happen.

Step 12: The code, as a QR picture

uv add qrcode==8.2
Resolved 32 packages in ...
Checked 29 packages in ...

A new module, registrations/codes.py:

"""Check-in codes as QR pictures (Chapter 46)."""
import qrcode
from django.utils.safestring import mark_safe
from qrcode.image.svg import SvgPathImage


def qr_svg(text):
    """Return text as a QR code: an <svg> for the page.

    One path, no style element, so it obeys the page's
    security policy (Chapter 59) and scales with CSS. The
    text is an address Otahque made, so it is safe.
    """
    image = qrcode.make(text, image_factory=SvgPathImage,
                        border=2)
    return mark_safe(image.to_string(encoding='unicode'))

mark_safe() tells the template not to escape the SVG. That is only right because Otahque made the text inside it; never mark anything a member typed as safe. In registrations/views.py, add from .codes import qr_svg above from .forms import, and above door_event():

# Chapter 46: check-in codes and the door.

class PlaceCodeView(DetailView):
    """The member's check-in code, as a QR picture.

    Only their own place (404, recorded). POST gives the
    place a new code; the old one stops working.
    """

    template_name = 'registrations/code.html'
    http_method_names = ['get', 'post']
    context_object_name = 'place'

    def get_object(self, queryset=None):
        """Return the member's own place."""
        return own_place(self.request,
                         self.kwargs['registration_id'],
                         Action.VIEW_CODE)

    def get_context_data(self, **kwargs):
        """Add the picture, unless the place is gone."""
        place = self.object
        held = place.status == Registration.Status.ACTIVE
        return super().get_context_data(**kwargs) | {
            'event': place.event,
            'qr': qr_svg(place.checkin_url()) if held else '',
        }

    def post(self, request, *args, **kwargs):
        """Give the place a new code."""
        place = self.get_object()
        place.new_checkin_ref()
        messages.success(request, 'Here is your new code. The '
                         'old one no longer works.')
        return redirect('registrations:code', place.pk)

The address, in registrations/urls.py, above the door’s:

    path('registrations/<int:registration_id>/code/',
         views.PlaceCodeView.as_view(), name='code'),

The page, a new file, registrations/templates/registrations/code.html:

{% extends "base.html" %}

{% block title %}Check-in code | Otahque{% endblock %}

{% block content %}
  <h1>Your check-in code</h1>
  {% if qr %}
    <section class="qr-card" aria-labelledby="qr-title">
      <h2 id="qr-title">{{ event.title }}</h2>
      <p>{% include "events/when.html" %}</p>
      <div class="qr-code" role="img"
           aria-label="Check-in code for {{ event.title }}">
        {{ qr }}</div>
      <p class="font-semibold">Show this at the door.</p>
      <p class="text-sm">An organizer scans it to check you
        in. It is not a ticket by itself: it works only for
        the event's organizers, signed in.</p>
    </section>
    <form method="post" class="space-y-2">
      {% csrf_token %}
      <p class="text-sm">Shared it by mistake? A new code
        stops the old one working.</p>
      <button type="submit" class="btn btn-outline btn-sm">
        Get a new code</button>
    </form>
  {% else %}
    <p>This place is cancelled, so it has no check-in
       code.</p>
  {% endif %}
  <p>
    <a href="{{ event.get_absolute_url }}">Back to the
      event</a>
  </p>
{% endblock %}

A link to it, in panel.html, above the cancel dialog’s include:

    <p><a href="{% url 'registrations:code' place.pk %}">
      Show my check-in code</a></p>

and in row.html, for My registrations, from {% elif now < place.event.starts_at %} to the end:

  {% elif now < place.event.starts_at %}
    {# Chapter 46: the code to show at the door. #}
    <a href="{% url 'registrations:code' place.pk %}">
      Check-in code</a>
    <a href="{% url 'registrations:cancel' place.pk %}">
      Cancel my place</a>
    {% if place.asks %}
      <a href="{% url 'registrations:answers' place.pk %}">
        Change my answers</a>
    {% endif %}
  {% elif now < place.event.ends_at %}
    <a href="{% url 'registrations:code' place.pk %}">
      Check-in code</a>
  {% endif %}
</li>

The card, in static/otahque/source.css, above the door page’s styles:

  /* Chapter 46: the member's code, a card to show at the
     door. */
  .qr-card {
    display: grid;
    justify-items: center;
    gap: 0.5rem;
    max-width: 24rem;
    padding: 1.25rem;
    border: 1px solid var(--color-base-300);
    border-top: 6px solid var(--color-primary);
    border-radius: var(--radius-box);
    background-color: var(--color-base-100);
    text-align: center;
  }
  .qr-code svg {
    width: min(18rem, 70vw);
    height: auto;
  }

The tests, in a new file, registrations/tests/test_codes.py:

"""Check-in codes, shown as QR pictures (Chapter 46)."""
from django.test import TestCase
from django.utils import timezone

from audit.models import AuditEvent

from .test_registrations import soon, url, verified


class CodeTests(TestCase):
    """A random reference per place, shown as a QR code."""

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

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

    def test_each_place_has_its_own_reference(self):
        raj = verified('raj@example.org')
        other = self.event.register(raj, timezone.now())
        self.assertEqual(len(self.place.checkin_ref), 22)
        self.assertNotEqual(self.place.checkin_ref,
                            other.checkin_ref)

    def test_the_code_page_shows_an_svg_without_style(self):
        page = self.client.get(url('code', self.place.pk))
        self.assertContains(page, '<svg')
        self.assertContains(page, 'Show this at the door.')
        self.assertNotContains(page, '<style')

    def test_someone_elses_code_is_missing_and_recorded(self):
        raj = verified('raj@example.org')
        self.client.force_login(raj)
        page = self.client.get(url('code', self.place.pk))
        self.assertEqual(page.status_code, 404)
        self.assertTrue(AuditEvent.objects.filter(
            actor=raj, action='view_code',
            outcome='refused').exists())

    def test_a_cancelled_place_has_no_code(self):
        self.place.cancel(timezone.now())
        page = self.client.get(url('code', self.place.pk))
        self.assertNotContains(page, '<svg')

    def test_a_new_code_replaces_the_old_one(self):
        old = self.place.checkin_ref
        self.client.post(url('code', self.place.pk))
        self.place.refresh_from_db()
        self.assertNotEqual(self.place.checkin_ref, old)
npm run build
uv run python manage.py test registrations.tests.test_codes
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s

OK

Step 13: Who came, on the attendee list

In registrations/models.py, in Registration, above checkin_url():

    def checkin_or_none(self):
        """Return the current CheckIn, or None."""
        checkin = getattr(self, 'checkin', None)
        if checkin is not None and checkin.is_current():
            return checkin
        return None

In AttendeesView, get_queryset() reads each place’s check-in with it:

    def get_queryset(self):
        """Places held now, with each member and profile."""
        return self.event.registrations.active().with_people(
        ).select_related('checkin')

and get_context_data() adds, below the cancellation counts, with a helper after the class:

            # Chapter 46: who came, counted from the rows
            # already read, and who may check members in.
            'attendance': attendance(context['places']),
            'can_check_in': self.event.can_check_in(
                self.request.user),
        }


def attendance(places):
    """Count who came and who has not, among places held."""
    came = sum(1 for place in places
               if place.checkin_or_none() is not None)
    return {'came': came, 'not_yet': len(places) - came}

Counting from the rows already read costs no query; asking whether the viewer may check people in costs one, so Chapter 38’s query count changes on purpose, from 10 to 11, in registrations/tests/test_questions.py:

        path = url('attendees', self.event.pk)
        # Chapter 46: one more, for whether this member may
        # check people in; who came is read with the places.
        with self.assertNumQueries(11):

and the same assertNumQueries(10) further down, after a ninth member registers, becomes assertNumQueries(11) too.

In registrations/templates/registrations/attendees.html, below the cancellation counts:

  {# Chapter 46: who came. #}
  <p class="attendance-counts">
    <span class="badge badge-success">{{ attendance.came }}
      checked in</span>
    <span class="badge">{{ attendance.not_yet }} not
      yet</span>
    {% if can_check_in %}
      <a href="{% url 'registrations:door' event.pk %}">
        Open check-in</a>
    {% endif %}
  </p>

a column heading below Name:

            <th scope="col">Came</th>

and its cell, below each member’s name:

              <td>
                {% if place.checkin.is_current %}
                  <span class="badge badge-success">Checked
                    in</span>
                {% else %}
                  <span class="badge">Not yet</span>
                {% endif %}
              </td>
              <td>{{ person.email }}</td>

The style, in static/otahque/source.css, above .form-actions:

  /* Chapter 46: who came, on the attendee list. */
  .attendance-counts {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 0.5rem 1rem;
  }

The test, in a new file, registrations/tests/test_attendance.py:

"""Who came, on the attendee list (Chapter 46)."""
from django.test import TestCase
from django.utils import timezone

from config.helpers import in_group

from .test_checkin import tonight
from .test_registrations import url, verified


class AttendanceTests(TestCase):
    """Badges and counts for the event's organizers."""

    @classmethod
    def setUpTestData(cls):
        cls.event = tonight(capacity=3)
        cls.sam = in_group('sam@example.org', 'Organizers')
        cls.event.add_organizer(cls.sam)
        now = timezone.now()
        cls.sai = cls.event.register(
            verified('sai@example.org'), now)
        cls.event.register(verified('raj@example.org'), now)

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

    def test_attendance_on_the_attendee_list(self):
        self.client.post(url('checkin', self.sai.pk))
        page = self.client.get(url('attendees', self.event.pk))
        self.assertContains(page, '1\n      checked in')
        self.assertContains(page, '1 not\n      yet')
npm run build
uv run python manage.py test registrations.tests.test_attendance
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s

OK

Step 14: Two scans at once

In registrations/tests/test_races.py, the imports become:

"""Promotion and check-in at the same moment (Chapter 46).

PostgreSQL only, like Chapter 33's RaceTests: each test
commits its rows, so other threads see them.
"""
from datetime import timedelta
from unittest import mock

from django.test import TransactionTestCase, skipUnlessDBFeature
from django.utils import timezone

from audit.models import AuditEvent
from events.models import Event
from registrations.models import CheckIn, Registration

from .test_registrations import at_once, soon, verified

and at the end:

@skipUnlessDBFeature('has_select_for_update')
class ScanRaceTests(TransactionTestCase):
    """Two organizers scan one code at the same moment."""

    def test_two_scans_check_in_once(self):
        starts = timezone.now() + timedelta(hours=1)
        event = soon(starts_at=starts,
                     ends_at=starts + timedelta(hours=2),
                     registration_closes_at=starts,
                     cancellation_deadline=starts)
        # check_in() records who did it; the permission check
        # is the view's. A plain member keeps this test free of
        # the permissions a serialized_rollback test empties.
        sam = verified('sam@example.org')
        place = event.register(verified('sai@example.org'),
                               timezone.now())

        def scan():
            fresh = Registration.objects.get(pk=place.pk)
            fresh.check_in(sam, 'code', timezone.now())
            return 'checked in'

        outcomes = at_once(scan, scan)
        self.assertCountEqual(outcomes, ['checked in',
                                         ['already_checked_in']])
        self.assertEqual(CheckIn.objects.count(), 1)
        self.assertEqual(AuditEvent.objects.filter(
            action='check_in').count(), 1)
uv run python manage.py test registrations.tests.test_races
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s

OK

Step 15: The design notes

In docs/design/registration.md, the bullet about cancelling without the lock becomes:

- Since Chapter 46, cancelling a place locks the event
  too, because it may give the place to the first member
  waiting in the same transaction; so a cancel can be
  told "busy". A count made just before a cancel still
  sees the place: that can only refuse, never oversell.

remove “Waitlist and check-in: Chapter 46.” from “Not here”, and at the end:

## Three facts: a place, a turn, attendance (Chapter 46)

| Fact       | Model          | States                   |
|------------|----------------|--------------------------|
| A place    | Registration   | active, cancelled        |
| A turn     | WaitlistEntry  | waiting, promoted, left, |
|            |                | closed                   |
| Attendance | CheckIn        | current, undone          |

| From    | Event                     | To        | Who       |
|---------|---------------------------|-----------|-----------|
| none    | join (full, open)         | waiting   | member    |
| waiting | a place frees, while open | promoted  | Otahque   |
| waiting | leave                     | left      | member    |
| waiting | registration ends         | closed    | scheduler |
| active  | cancel                    | cancelled | member    |
| active  | check in, in the window   | current   | organizer |
| current | undo, in the window       | undone    | organizer |
| undone  | check in again            | current   | organizer |

- Joining needs what a place needs: a verified email,
  and the phone, facts, and answers the event asks. The
  answers wait on the entry; the profile keeps the rest.
- Promotion is register(..., source='waitlist') on the
  locked event, from cancel() and from a capacity rise.
  A member who now owes an answer is skipped, keeps the
  turn, and is emailed once.
- One waiting entry per member and event (the
  waitlist_one_waiting rule); entries are never deleted.
- A check-in reference (checkin_ref, 22 random
  characters) per place, stored as it is: a key to find
  the place, not a password. Only the event's current
  organizers, signed in, can use it, by POST. A new code
  stops the old one; a cancelled place's code is refused.
- One CheckIn per place; an undo is recorded on it, and
  every check-in, undo, and refusal is an AuditEvent.
- The window: from 30 minutes to a day before the start
  (default 2 hours) until the end or an hour after
  (default the end), chosen per event.

In docs/design/permissions.md, the Chapter 46 line leaves “Planned rows”, and at the end:

## Check-in (Chapter 46)

The door page, its buttons, and the scan answer the
same people. A check-in code never replaces these checks.

| Person          | Door page | Scan a code |
|-----------------|-----------|-------------|
| Visitor         | sign in   | sign in     |
| The member      | 403       | 403         |
| Other organizer | 403       | 403         |
| Administrator   | 403       | 403         |
| Organizer       | ok        | ok          |

- Every refusal by a signed-in person is a refused
  check_in AuditEvent, with its reason when the place or
  the window refused it. A draft's door page: 404.
- A member sees only their own code and waitlist entry:
  another member's is 404, recorded (view_code,
  leave_waitlist).
- Volunteers, a separate role: Chapter 70.

Step 16: The Milestone 3 trace

Chapter 34 closed Milestone 2 with docs/acceptance/M2.md: each rule, the cases, and the tests that check them. Milestone 3, event-day operations, ends here, and gets the same, in a new file, docs/acceptance/M3.md:

# M3 acceptance trace: event-day operations

Chapters 35 to 46. The milestone's scenario: reminders
reach registered members; a cancelled place goes to the
waitlist; on the day, Sam checks in attendees, and each
attendance is recorded once. Each acceptance check, the
cases that prove it, and the tests that check each case.
Names are `Class.test_name`; the app is in brackets.
`TraceTests` (config) fails if a named test is missing.

Evidence: `check.py` passes, with the race tests run on
PostgreSQL (they skip on SQLite). Not reached until the
author's review: drafted in Chapter 46.

## Tasks run outside the request

- Registering queues an email and sends nothing (events):
  `QueueTests.test_registering_queues_and_sends_nothing`
- A rolled-back change queues nothing (events):
  `QueueTests.test_a_rolled_back_change_queues_nothing`
- The worker, a separate process, sends it (events):
  `WorkerTests.test_the_worker_sends_a_queued_email`
- Reminders come from a scheduled command (events):
  `ReminderTests.test_the_due_reminder_is_queued_once`,
  `ReminderTests.test_a_moved_event_is_not_reminded_twice`

## Retries do not duplicate

- Running a delivery twice sends once (events):
  `SendTests.test_running_twice_sends_once`
- A failure is retried, then given up (events):
  `SendTests.test_a_failure_is_retried_then_given_up`
- A lost enqueue is found again (events):
  `StaleTests.test_an_old_queued_delivery_is_enqueued_again`
- A failed send keeps the place (events):
  `FailureTests.test_a_failed_send_keeps_the_place`

## The waitlist gives a place once

- First come, first served (registrations):
  `JoinTests.test_members_wait_in_the_order_they_joined`,
  `PromotionTests.test_a_cancel_gives_the_place_to_the_first`,
  `PromotionTests.test_the_next_one_moves_up`
- Promotion under the lock, at the same moment
  (registrations, PostgreSQL):
  `PromotionRaceTests.test_two_cancels_and_a_newcomer`,
  `RaceTests.test_a_cancel_during_a_request_only_refuses`
- A higher capacity promotes in order (registrations):
  `PromotionTests.test_a_higher_capacity_promotes_in_order`
- A member who owes an answer is passed over, keeps the
  turn, and is told (registrations):
  `PromotionTests.test_a_member_who_owes_an_answer_is_skipped`,
  `PromotionTests.test_answering_keeps_the_turn`
- No promotion once registration has closed; the waitlist
  closes, and each member is told (registrations):
  `PromotionTests.test_nobody_is_promoted_once_closed`,
  `ClosingTests.test_closed_registration_closes_it_and_tells`

## Check-in is recorded once

- By name, at the door (registrations):
  `DoorTests.test_check_in_by_name_with_htmx_swaps_the_row`
- By code: opening the link changes nothing; confirming
  checks in (registrations):
  `ScanTests.test_opening_the_link_changes_nothing`,
  `ScanTests.test_confirming_checks_in_by_code`
- Twice, or at the same moment, is once (registrations):
  `CheckInRuleTests.test_twice_is_refused`,
  `ScanRaceTests.test_two_scans_check_in_once`
- An undo is kept, and every step recorded
  (registrations):
  `CheckInRuleTests.test_undo_then_again_one_row_three_records`
- Only inside the event's window (registrations):
  `CheckInRuleTests.test_outside_the_window_is_refused`,
  `WindowTests.test_an_organizer_may_choose_the_window`

## Refused codes and roles

- A code that was replaced, or never existed
  (registrations):
  `CodeTests.test_a_new_code_replaces_the_old_one`,
  `ScanTests.test_a_replaced_code_is_missing`,
  `ScanTests.test_an_unknown_code_is_missing`
- A cancelled place (registrations):
  `CheckInRuleTests.test_a_cancelled_place_is_refused`,
  `ScanTests.test_a_cancelled_place_says_so_and_is_refused`
- The member's own phone, or another organizer, recorded
  (registrations):
  `ScanTests.test_the_member_cannot_check_themselves_in`,
  `DoorTests.test_another_organizer_is_refused_and_recorded`
- Another member's code or waitlist entry, recorded
  (registrations):
  `CodeTests.test_someone_elses_code_is_missing_and_recorded`,
  `JoinTests.test_someone_elses_entry_is_missing_and_recorded`

## Exports are authorized

- The attendee download, for organizers and the
  administrator only, each one recorded (registrations):
  `DownloadMethodTests.test_for_an_organizer`,
  `DownloadMethodTests.test_for_anyone_else`,
  `DownloadTests.test_each_download_is_recorded`,
  `DownloadTests.test_the_administrator_may_download`

## Demonstration

On a copy of the database, with the worker running
(`db_worker`) and Mailpit open:

1. Import sample registrations:
   `uv run python manage.py import_registrations` with a
   small file, dry run first (docs/runbooks/import.md).
2. Run `uv run python manage.py send_due_reminders`; the
   worker sends the reminders that are due; Mailpit
   shows them.
3. Fill an event, join its waitlist as Sai, cancel a
   place as Raj: Sai has the place, and Mailpit shows
   "A place came up".
4. On the event day, as Sam: open Check-in, find Raj by
   name and check him in; scan Sai's code with a phone,
   or open its address, and press Check in.
5. The attendee list shows both as checked in.

## Known limits

- "Sent" is what the mail server accepted, not proof
  that a member read it (Chapter 44).
- There is no API yet (Chapters 47 to 54).
- Check-in needs a network: no offline mode is promised.
- Volunteers cannot check in until Chapter 70.
- The scan was tried in a browser, not with phone
  cameras; the demonstration does that by hand.

Chapter 34’s TraceTests checks that every test M2.md names exists; it now checks M3.md too. In config/tests/test_acceptance.py, below TRACE:

# Chapter 46: the trace for the third milestone.
M3 = settings.BASE_DIR / 'docs/acceptance/M3.md'

and the class becomes a helper and two tests:

def missing(trace):
    """Return the tests a trace names that do not exist."""
    names = NAME.findall(trace.read_text(encoding='utf-8'))
    found = {(c.__name__, m) for c in test_classes()
             if isinstance(c, type) for m in dir(c)}
    return len(names), [f'{c}.{m}' for c, m in names
                        if (c, m) not in found]


class TraceTests(SimpleTestCase):
    """The acceptance traces, checked against the tests."""

    def test_every_named_test_exists(self):
        count, absent = missing(TRACE)
        self.assertGreater(count, 40)
        self.assertEqual(absent, [])

    def test_every_m3_test_exists(self):
        count, absent = missing(M3)
        self.assertGreater(count, 20)
        self.assertEqual(absent, [])
uv run python manage.py test config.tests.test_acceptance
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s

OK

Step 17: In a browser, the checks, and the commit

Run the server, fill an event, join its waitlist as one member and cancel as another; open the check-in code; then, as the organizer, on a phone-sized window, find a member on the door page, check them in, undo, and open another member’s code address and press Check in. Figure 46.5 shows the door and the code.

Two phone screenshots, 390 pixels wide. Left, Check-in: Tonight’s meetup, with a dark bar saying 1 of 2 checked in, a large search box and a Search button, and two rows: Raj, Not yet, with a big blue Check in button; Sai, Checked in at a time, with an Undo button. Right, Your check-in code: a card for Full clinic with its date, a large QR code, Show this at the door, and a note that the code works only for the event’s organizers; below, Get a new code.
Figure 46.5 — The door page, and a member’s code.
uv run python check.py
== python manage.py check
System check identified no issues (0 silenced).
== python manage.py makemigrations --check --dry-run
== python manage.py test --parallel
Found 620 test(s).
System check identified no issues (0 silenced).
Ran 620 tests in ...s
OK
== all checks passed
git add .
git status --short
git commit -m "Add waitlists and check-in"
A  audit/migrations/0006_waitlist_actions.py
M  audit/models.py
M  config/settings.py
M  config/tests/test_acceptance.py
M  config/tests/test_public.py
A  docs/acceptance/M3.md
M  docs/design/permissions.md
M  docs/design/registration.md
M  events/emails.py
M  events/forms.py
M  events/management/commands/send_due_reminders.py
A  events/migrations/0014_checkin_window.py
M  events/models.py
M  events/templates/events/detail.html
M  events/templates/events/event_fields.html
M  events/tests/test_events.py
M  events/tests/test_reminders.py
A  events/tests/test_window.py
M  events/views.py
M  pyproject.toml
A  registrations/codes.py
A  registrations/migrations/0007_waitlist.py
A  registrations/migrations/0008_checkin_ref.py
A  registrations/migrations/0009_fill_checkin_ref.py
A  registrations/migrations/0010_checkin_ref_unique.py
A  registrations/migrations/0011_checkin.py
M  registrations/models.py
M  registrations/templates/registrations/attendees.html
A  registrations/templates/registrations/code.html
M  registrations/templates/registrations/details.html
A  registrations/templates/registrations/door.html
A  registrations/templates/registrations/door_swap.html
M  registrations/templates/registrations/mine.html
M  registrations/templates/registrations/panel.html
M  registrations/templates/registrations/row.html
A  registrations/templates/registrations/scan.html
A  registrations/tests/test_attendance.py
A  registrations/tests/test_checkin.py
A  registrations/tests/test_closing.py
A  registrations/tests/test_codes.py
A  registrations/tests/test_door.py
M  registrations/tests/test_lists.py
A  registrations/tests/test_promotion.py
M  registrations/tests/test_questions.py
A  registrations/tests/test_races.py
M  registrations/tests/test_registrations.py
A  registrations/tests/test_scan.py
A  registrations/tests/test_waitlist.py
M  registrations/urls.py
M  registrations/views.py
M  static/otahque/site.css
M  static/otahque/source.css
M  uv.lock
[main 1a2b3c4] Add waitlists and check-in
 53 files changed, 2519 insertions(+), 57 deletions(-)
 create mode 100644 audit/migrations/0006_waitlist_actions.py
 create mode 100644 docs/acceptance/M3.md
 create mode 100644 events/migrations/0014_checkin_window.py
 create mode 100644 events/tests/test_window.py
 create mode 100644 registrations/codes.py
 create mode 100644 registrations/migrations/0007_waitlist.py
 create mode 100644
    registrations/migrations/0008_checkin_ref.py
 create mode 100644
    registrations/migrations/0009_fill_checkin_ref.py
 create mode 100644
    registrations/migrations/0010_checkin_ref_unique.py
 create mode 100644 registrations/migrations/0011_checkin.py
 create mode 100644
    registrations/templates/registrations/code.html
 create mode 100644
    registrations/templates/registrations/door.html
 create mode 100644
    registrations/templates/registrations/door_swap.html
 create mode 100644
    registrations/templates/registrations/scan.html
 create mode 100644 registrations/tests/test_attendance.py
 create mode 100644 registrations/tests/test_checkin.py
 create mode 100644 registrations/tests/test_closing.py
 create mode 100644 registrations/tests/test_codes.py
 create mode 100644 registrations/tests/test_door.py
 create mode 100644 registrations/tests/test_promotion.py
 create mode 100644 registrations/tests/test_races.py
 create mode 100644 registrations/tests/test_scan.py
 create mode 100644 registrations/tests/test_waitlist.py

If something goes wrong

Table 46.3 — Recovery for Chapter 46
What you see Likely cause What to do
IntegrityError: UNIQUE constraint failed on checkin_ref The reference was added in one migration Use the three migrations of Step 7; nothing was saved, so run them again
Nobody is promoted after a cancel Registration has closed, or the members waiting owe an answer Check the closing time; look for skipped_at on the entries
A promoted member gets no email No worker is running Start db_worker (Chapter 44)
The race tests skip The tests ran on SQLite Run them with PostgreSQL, as check.py does
Check-in is refused Outside the event's window, or the place is cancelled Read the door page's notice; change the window on the edit page
The scan page says 403 The person is not a current organizer of that event Sign in as one; volunteers come in Chapter 70
The QR code is empty The place is cancelled A held place has a code; register again
PAGE 003

Verify Your Work

Work through Table 46.4 from the folder that holds manage.py, with Otahque on PostgreSQL.

Table 46.4 — Verification checklist for Chapter 46
Check Command or action Expected result
Starting point test --parallel Found 569 test(s); OK
The waitlist model makemigrations, then migrate registrations 0007 and audit 0006 applied
Joining and leaving test registrations.tests.test_waitlist Red first; then 11 tests OK
Promotion test registrations.tests.test_promotion Red first; then 6, and after Step 5, 7 tests OK
The races test registrations.tests.test_races; test registrations OK, on PostgreSQL; Chapter 33's overlap test changed on purpose
Closing test registrations.tests.test_closing; test events.tests.test_reminders Red first; then OK; Chapter 44's report test changed on purpose
References migrate registrations 0008 to 0010 applied; every existing place has its own reference
The window test events.tests.test_window; test events.tests.test_events Red first; then OK; Chapter 44's field count changed on purpose
Check-in test registrations.tests.test_checkin, test_door, test_scan, test_attendance 5, 7, 6, and 1 tests OK
Public pages test config.tests.test_public Red, then OK: the route test fills <str:> too
Codes test registrations.tests.test_codes 5 tests OK
The trace test config.tests.test_acceptance 2 tests OK
In a browser Join, cancel, the code page; the door at 390 and 1280 px 1st in line; the place promoted; no reload on the door
All checks uv run python check.py == all checks passed; Ran 620 tests
Commit git log --oneline -1 Add waitlists and check-in
Not verified A phone camera scanning the code; macOS and Linux shells Scan a code with your own phone, as in the demonstration in M3.md

The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 45 checkpoint with a reader’s data, against PostgreSQL 18; commands that write files ran once. The race tests ran on PostgreSQL. In Microsoft Edge, at 390 and 1280 pixels, a Playwright script joined a full event’s waitlist as Sai (her panel changed in place to “1st in line” and the live region spoke), cancelled Raj’s place, saw Sai’s panel show her place and her code page a QR picture, then, as Sam on the door page, narrowed the list by typing, checked Sai in (the row and the count changed in place), opened Raj’s code address, which showed a Check in button and checked nobody in, pressed it, and saw the attendee list with both checked in. Two sample events were added for those checks and deleted afterwards.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 1 Why are a place, a turn, and attendance three records, not three fields on one?

Flip to check your answerFold answer back

Answer. They change at different times, for different people, with different rules: a member joins and leaves a waitlist, Otahque promotes, an organizer checks in. Separate records keep each set of states small, and the history of each.

Que. 2 Why does cancel() lock the event now, when Chapter 31’s single UPDATE was enough?

Flip to check your answerFold answer back

Answer. Because cancelling now also gives the place to the first member waiting. The two changes must happen together, or a newcomer’s request can take the freed place between them. Under the lock, a request that comes meanwhile waits, counts again, and finds the event full.

Que. 3 Why can’t the check-in code be stored only as a hash?

Flip to check your answerFold answer back

Answer. The member’s page draws the code every time it is opened, and a hash cannot be turned back into it. Otahque stores the random reference as it is, because it is only a key to find a place: what decides is the organizer’s sign-in, and a POST.

Que. 4 Two organizers scan Sai’s code at the same moment. What makes it one check-in?

Flip to check your answerFold answer back

Answer. check_in() locks the place’s row first, so the second request waits, then finds the first one’s CheckIn and is told “Already checked in”. The one-to-one link is the backstop in the database.

Que. 5 A member waiting owes an answer to a question added after they joined. What happens when a place frees?

Flip to check your answerFold answer back

Answer. Otahque skips them, keeps their turn, emails them once, and gives the place to the next member who owes nothing. When they answer, on the same details page, they keep their turn for the next place.

Mini-Challenge

A visitor who is not signed in opens a full event. They should read that it is full, and see no Join the waitlist button, because they cannot join without signing in. Write a test, in registrations/tests/test_full.py, that checks both.

Hint: full() in test_waitlist.py makes a full event; do not sign in.

Model answer:

"""A full event, signed out (Chapter 46 challenge)."""
from django.test import TestCase

from registrations.tests.test_waitlist import full


class SignedOutWaitlistTests(TestCase):
    """A visitor sees that the event is full, and no button."""

    def test_full_and_no_waitlist_button(self):
        event = full()
        page = self.client.get(event.get_absolute_url())
        self.assertContains(page, 'This event is full.')
        self.assertNotContains(page, 'Join the waitlist')
uv run python manage.py test registrations.tests.test_full
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s

OK

The model answer was run and then removed; the chapter’s checkpoint does not include it.

What We Learned

  • Separate facts get separate records, each with a short list of states and the changes between them, written down as a table.
  • A change made of two steps that others can race, such as freeing a place and filling it, happens in one transaction, under one lock.
  • Reuse the rules: a promotion is a registration made by Otahque, through register().
  • A unique column on a table with rows takes three migrations: add it empty, fill each row, make it unique.
  • A code that opens a page is a key, not authority; authority is who is signed in, and a POST.
  • Lock the row, then check, then write: one check-in, even from two phones.
  • A milestone is reached when each of its promises points at tests that pass.

Key terms

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

Table 46.5 — Key terms from Chapter 46
Term Meaning
State Where a record is: waiting, promoted, left, closed.
Transition An allowed change from one state to another, with its rule.
Waitlist Members waiting for a place, in the order they joined.
Promotion Giving a freed place to the first member waiting.
Partial unique constraint Unique only among rows that match a condition.
Data migration A migration that changes rows, not the schema.
Check-in reference A random key that finds one place; not a password.
Check-in window When an event's members may be checked in.
Idempotent Doing it twice has the effect of doing it once.
Acceptance trace A milestone's checks, each tied to named tests.

Readiness checkpoint: you are ready for Chapter 47 when uv run python check.py ends with “all checks passed” and 620 tests, the race tests pass on PostgreSQL, a cancelled place goes to the first member waiting in your browser, the door page checks a member in once, and git log --oneline -1 shows this chapter’s commit. Milestone 3 is drafted; it counts as reached once its trace has been reviewed.

Git Commit

Your Chapter 46 work was committed once, in Step 17, as “Add waitlists and check-in”: the models and their seven migrations, the views, URLs, and templates, the emails and the scheduled command, the code module and the declared package, the stylesheet and its compiled CSS, the nine new test modules and the six declared test changes, the design notes, and the Milestone 3 trace. If you kept the Mini-Challenge, commit it on its own:

git add registrations/tests/test_full.py
git commit -m "Check a full event as a visitor"
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, to an incident at the door and to choosing how places are offered. They are extension questions, not a gate to the next chapter. Proof files are run with uv run python manage.py shell -v 0 -c "exec(open('NAME').read())" and deleted afterwards.

L1 (Junior): Registration, waiting, and attendance: what is the difference?

What the interviewer is testing: Can you keep three facts apart?

Flip to check your answerFold answer back

Perfect answer: Registering gives a member a place, which counts against the capacity. Waiting means the event was full and the member is in line for a place; it counts against nothing. Attendance means they came, which only an organizer at the door can record. Table 46.6 puts them side by side.

Table 46.6 — Three facts
Fact Record Counts as taken Set by
A place Registration Yes, while active The member, or a promotion
A turn WaitlistEntry No The member
Attendance CheckIn No An organizer

Behind the scenes:

Registration  active     (Sai's place)
WaitlistEntry promoted   (how she got it)
CheckIn       18:05, Sam (she came)

Code proof: the waitlist’s tests:

Found 11 test(s).
Creating test database for alias 'default'...
...
Ran 11 tests in ...s

OK

Common mistakes:

  • Treating “registered” as “came”: a list of places is not a list of attendees.
  • Counting waiting members against the capacity.

Follow-up the interviewer might ask:

  • Which of the three does Chapter 72 need for ratings? (Attendance: only members who came may rate.)

L2 (Mid-Level): Raj cancels; Sai and Soni are waiting. Predict what happens

What the interviewer is testing: Can you trace a state change through a transaction?

Flip to check your answerFold answer back

Perfect answer: cancel() locks the event, changes Raj’s place to cancelled, and calls fill_from_waitlist() in the same transaction. Sai joined first, so register() runs for her with source='waitlist', every rule checked; her entry becomes promoted, with the place it became, and an email is queued. The event is full again, so Soni stays waiting, now first in line. Only when the transaction commits does anyone see the change, all of it at once.

A numbered flow of five cards. 1, Raj cancels: the event is locked. 2, his place is cancelled. 3, Sai joined first: register() for her, source waitlist. 4, full again: Soni waits, now 1st in line. 5, commit: every change at once.
Figure 46.6 — One cancel, one promotion.

Behind the scenes:

lock event 7
UPDATE place 41: cancelled
INSERT place 42: Sai, source=waitlist
UPDATE entry 3: promoted, place 42
INSERT delivery: promoted:42:Sai
COMMIT

Code proof: a full clinic, two members waiting, one cancel:

"""Who gets a freed place; all of it rolled back after."""
from django.db import transaction
from django.utils import timezone

from registrations.tests.test_registrations import soon, verified

now = timezone.now()
with transaction.atomic():
    event = soon(capacity=1, title='Proof clinic')
    raj = event.register(verified('proof-raj@example.org'), now)
    for name in ('sai', 'soni'):
        member = verified(f'proof-{name}@example.org')
        event.join_waitlist(member, now)
    raj.cancel(now)
    for entry in event.waitlist.all():
        print(entry.member.email, entry.status)
    # Nothing is kept, and no email is ever enqueued.
    transaction.set_rollback(True)
proof-sai@example.org promoted
proof-soni@example.org waiting

Common mistakes:

  • Promoting in the view after cancel() returns: the place is free and unlocked between the two.
  • Forgetting that a promoted member must still meet the event’s rules.

Follow-up the interviewer might ask:

  • What if Sai owes an answer to a new question? (She is skipped, keeps her turn, and is told once; Soni gets the place if she owes nothing.)

L3 (Senior): Defend storing the check-in reference as it is

What the interviewer is testing: Can you tell a lookup key from a credential?

Flip to check your answerFold answer back

Perfect answer: Passwords are hashed because a password alone proves who you are. Otahque’s reference proves nothing alone: it only finds a place, and the page it opens checks that a current organizer of that event is signed in, and changes something only on a POST. A visitor is sent to sign in; the member, or anyone else, is refused and recorded. So the reference can be stored as it is, which lets the member’s page draw the code every time. A hash would lose that, and a signature would make every code change when the secret key is rotated, with no way to stop one code alone. If the code ever became authority by itself, a kiosk with no staff, the answer would change.

A numbered flow of five cards. 1, a password: proof by itself, so hashed. 2, a check-in reference: finds a place, proves nothing. 3, authority: an organizer, signed in, by POST. 4, stored as it is: the code can be drawn again. 5, revisit if the code ever acts alone.
Figure 46.7 — A key to look up, not a credential.

Behind the scenes:

visitor            302 to sign in
the member         403, recorded
another organizer  403, recorded
event's organizer  200, then POST to check in

Code proof: the reference, opened by a visitor and by its own member:

"""A scan is a lookup: what the reference alone can do."""
from django.test import Client

from registrations.models import Registration

place = Registration.objects.filter(status='active').first()
address = f'/check-in/{place.checkin_ref}/'
for who in ('a visitor', 'the member'):
    client = Client(HTTP_HOST='localhost')
    if who == 'the member':
        client.force_login(place.member)
    answer = client.get(address)
    print(f'{who:11} {answer.status_code}')
a visitor   302
the member  403

Common mistakes:

  • Hashing everything that looks like a token, whatever it is for.
  • Checking in on GET, so a link preview checks members in.

Follow-up the interviewer might ask:

  • How would you stop a code that was posted online? (Get a new code: the old reference stops finding the place.)

L4 (Staff): A member appears twice as checked in

What the interviewer is testing: Can you diagnose a race at the door, looking ahead to Chapter 54’s live counts?

Flip to check your answerFold answer back

Perfect answer: Two helpers scanned the same code a second apart, and an earlier version wrote two records. The check read “not checked in”, then wrote, in two steps that two requests could interleave. The fix has two layers: lock the place’s row before checking, so the second request waits and then finds the first one’s record; and one CheckIn per place, a one-to-one link the database enforces, as a backstop. A test with two threads proves it on PostgreSQL. When Chapter 54 pushes the count live to every organizer’s phone, the count stays right because the row does.

A numbered flow of five cards. 1, two phones scan one code. 2, both read not yet, both write. 3, lock the place’s row before checking. 4, one CheckIn per place, in the database. 5, a two-thread test on PostgreSQL.
Figure 46.8 — One check-in from two phones.

Behind the scenes:

A: lock place 41   check: none   write   commit
B: lock place 41 ... waits ...  check: A's  refuse

Code proof: the race tests, on PostgreSQL:

Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s

OK

Common mistakes:

  • Fixing it with a check in the browser, which a second phone does not share.
  • Relying on the unique rule alone and showing members a server error.

Follow-up the interviewer might ask:

  • Why lock the place and not the event? (Check-ins for different members need not wait for each other, and the door should not hold up registration.)

L5 (Lead): Automatic promotion, or offers that expire?

What the interviewer is testing: Can you choose a product rule and say when you would change it?

Flip to check your answerFold answer back

Perfect answer: For Otahque’s free community events, automatic promotion is the better rule: a member who joined a waitlist wants the place; it fills places without an organizer watching; and it is one transition inside a lock Otahque already takes, with no timers. A member who no longer wants the place cancels, which promotes the next. Offers that expire, “accept within 24 hours”, suit paid or scarce places, where giving someone a place they did not confirm costs money; they need an offered state, an expiry task, reminders, and more ways to fail. I would revisit if promoted members often fail to come, which the check-ins now measure, or if paid events arrive. The Milestone 3 trace is the evidence the current rule works.

A numbered flow of five cards. 1, need: fill freed places fairly. 2, free events: members who wait want the place. 3, automatic: one transition, no timers. 4, offers: an expiry state, a task, reminders. 5, revisit if promoted members do not come.
Figure 46.9 — Choosing how a freed place is offered.

Behind the scenes:

waiting          waiting
  -> promoted      -> offered (24 h)
                       -> accepted | expired

Code proof: the Milestone 3 trace, checked:

Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s

OK

Common mistakes:

  • Choosing the more elaborate rule because large ticketing sites use it.
  • Changing the rule without the data, attendance of promoted members, that should decide it.

Follow-up the interviewer might ask:

  • How would you measure whether promoted members come? (Count check-ins among places with source waitlist, per event: Chapter 55’s reports.)

Next: Chapter 47, API design and HTTP contracts, which begins Milestone 4: Otahque’s events, offered to other programs through a documented API.

PAGE 006