Chapter 38 · Advanced admin and formsetsCHAPTER 38
Complete six-part pre-release for review. Five migrations (profile facts, event settings, questions and answers, an audit action, and the Administrators group's permission to read questions). The phone page moves to /register/details/; the attendee list becomes a class and answers only GET and HEAD (declared). The download of the table follows in Chapter 41.
Working towards: Event-day operations (Chapter 46). Reminders sent in the background, a waitlist that offers released places, and check-in that records each attendance once. All milestones
CHAPTER THIRTY-EIGHT
Advanced admin and formsets
Stage 5: Growing the application (Chapters 35 to 46)
Prerequisites: Chapters 9 to 37, including the Chapter 37 project with its 399 passing tests, EventUpdateView and save_edit() with its lock and version check (Chapters 33 and 37), the details page RegistrationDetailsView (Chapters 31 and 35), the attendee list (Chapter 31), the method tables, and the admin as the administrator’s tool (Chapter 23)
What you’ll build: Company, college, and website on the member’s profile, which an event can ask for; up to ten questions of eight kinds per event, built on the edit page with an inline formset and saved with the event under its lock; a registration form built at run time from those questions; answers kept with the place, shown beside each name on the attendee list, and changeable by the member until the start; questions copied with an event and archived, never deleted; and an admin with a date filter, an Upcoming and Past filter, member search, and read-only questions
Why This Matters
Sam’s next Python clinic needs to know each attendee’s level and whether they will bring a laptop. Soni’s book swap wants a T-shirt size for the volunteers. A hackathon needs everyone to tick “I agree to the code of conduct”. Every event asks different questions, and today Otahque can ask only one: a phone number.
The requirement has four sides. Sam must add, change, and remove a few questions on one page, and save them with the event, all or nothing. Members must answer them when they register, and a required question must be enforced on the server, not just marked in the browser. Sam, his co-organizers, and the administrator must see the answers beside each name. And some questions are not really about the event at all: “Which company are you from?” has the same answer for every event, and should not be typed every time.
Two Django tools carry most of this. A formset is a set of identical forms on one page, sent and checked together; an inline formset edits the rows that belong to one object, such as an event’s questions. And a form does not have to be written in advance: its fields can be added when it is built, from data. This chapter uses both, and closes with the admin improvements the administrator has been waiting for since Chapter 23.
By the end of the chapter, you will be able to:
choose where data with a varying shape belongs: columns, rows, or a JSON value;
build an inline formset, render it, and save it in the same transaction as its parent;
explain the management form, and what Django does when it is missing or tampered with;
build a form’s fields at run time, so its field names stay stable when questions change;
archive rows that other data depends on, instead of deleting them;
add list filters, a date hierarchy, search, and read-only inlines to the admin.
Out of scope: downloading the attendee table (Chapter 41), adding question rows without reloading the page (Chapter 45), file uploads as answers (not planned; Chapter 42 covers uploads), and saved question sets shared across events (Chapters 67 and 68).
The answers have two different shapes. A member’s company is one fact about the member, the same for every event that asks. An event’s own questions are different for every event: Sam’s clinic asks two, the hackathon asks five, the book swap one. Data with a fixed shape belongs in columns: the database knows their types and checks them. Data whose shape changes per event has three common homes, compared in Table 38.1.
Table 38.1 — Three ways to store per-event answers
Way
Strengths
Costs
A column per question
Typed, checked by the database
A migration for every question an organizer adds: impossible
A row per answer
A foreign key to the question; one answer per question enforced
A join or extra query per table; several choices need a format anyway
One JSON value per place
Saved with the place in one write; lists, numbers, true and false as they are
The database does not check the answers; the form and model must
Otahque uses both shapes for what they suit, which Figure 38.1 shows. Company, college, and website become columns on the member’s Profile, beside the phone number Chapter 31 put there; an event chooses which to ask for, as it chooses whether to ask for the phone. Each event’s own questions are rows of RegistrationQuestion, which the organizer edits, and the answers are one JSON value on the place, Registration.answers, such as {"q_12": "Some", "q_14": {"agreed": true, "at": "..."}}. Published comparisons of row-per-answer designs, often called entity-attribute-value (EAV), and PostgreSQL’s JSON type mostly favour JSON for a few dozen values per record, because reading a record needs no joins; they also warn against JSON for data with a fixed shape, which is why company and college are columns.
Figure 38.1 — Where each kind of answer is kept.
Under the Hood: why the keys are q_12, not 12
Django can look inside a JSON value in a query: Registration.objects.filter(answers__q_12='yes') finds every place where question 12 was answered yes. But a key made only of digits means something else in those lookups. Django reads answers__12 as “item 12 of a list”, because JSON lists are indexed by numbers, and finds nothing. Prefixing the key, q_12, keeps it a name, and the same name serves as the form field’s name, so a question has one key everywhere.
Formsets
New Concept: formsets
What problem exists? Sam’s questions are rows: he may send one, three, or ten at once, change two of them, and remove one. A single form describes one row.
What did people do before? Numbered field names by hand, such as label_1, label_2, and parsed them in the view.
What is it? A formset manages several copies of one form on a page. Each copy’s fields get a prefix and a number, such as questions-0-label and questions-1-label, so the copies never collide. formset_factory() makes a formset class from a form; modelformset_factory() from a model form; and inlineformset_factory(Event, RegistrationQuestion) makes one that edits the questions of one event.
Why use it? It checks every copy, offers empty copies for new rows (extra), a tick box to remove a row (can_delete), a limit (max_num), and a clean() method across all rows.
Now let’s use it. Step 4 builds one in plain Python; Steps 5 and 6 build Otahque’s.
Every formset sends a management form too: four hidden fields that say how many copies the page holds (TOTAL_FORMS), how many of those are existing rows (INITIAL_FORMS), and the limits. Without it, Django cannot know how many copies to read, so a formset without its management form is invalid, with the error “ManagementForm data is missing or has been tampered with”. Since Django 3.2 that is an error shown on the page, not a crash.
An inline formset finds existing rows by the hidden id field each copy sends, and only among the parent’s own rows. If a page sends the id of a row that belongs to another event, the formset finds nothing to change and saves nothing for that copy. That is safe, and it is quiet: the plan review’s probe showed it, and Step 6’s test pins it, because “nothing happened” is easy to mistake for “it worked”.
Forms built at run time
A form class usually lists its fields. But a form is an object, and self.fields is a dictionary that __init__() may change. Otahque’s registration form, DetailsForm, starts empty and adds one field per question the event asks, choosing the field type by the question’s kind. Each field is named by the question’s key, q_12, never by its label, so rewording “Python level” to “Your Python level” does not lose the answers already given. Figure 38.3, in Step 7, shows the mapping. The form also adds the phone number and profile facts the event asks for, filled in from the member’s profile.
Changing questions after people register
Questions change: Sam rewords one, adds one, decides another was a mistake. Table 38.2 lists the rules, decided before this chapter (D38.3).
Table 38.2 — What changing a question does
Change
Rule
Reword a question
Allowed; answers stay with the question's key
Add a question
Allowed; a required one applies only to new registrations
Remove a question
Archived: no longer asked; answers kept and still shown
Remove an answered choice
Refused: archive the question and add a new one
Change an agreement's text
Archive it and add a new agreement
More than ten questions
Refused
In practice: asking for less
Situation. An organizer adds “Date of birth” to check that attendees are adults.
Application. The question builder says what not to ask for: health details, government ID numbers, passwords; and to ask for an age range instead of a birth date. Every answer is personal data that Otahque must protect and, one day, delete (Chapters 59 and 65).
Consideration. The cheapest data to protect is data you never collected. A builder that makes the safer question the obvious one does more than a policy page.
Start from Chapter 37, in the folder containing manage.py, with Otahque on PostgreSQL 18, 399 passing tests, and the work committed (the last commit is “Turn the editing pages into classes”). Four migrations are new, one in each of accounts, events, registrations, and audit; no package changes. The new files are events/templates/events/questions.html, registrations/templates/registrations/answers.html, two widget templates, and registrations/tests/test_questions.py; registrations/templates/registrations/phone.html becomes details.html. Most of events, registrations, and accounts change, with the admin, the test helpers, three tests, the stylesheet source, and four design notes. The visible result: the edit page ends with a question builder; Register leads to a “few details” page when an event asks something; the attendee list gains a column per question; My registrations offers “Change my answers”; and the profile page gains company, college, and website. The chapter’s commands were checked in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.
The Custom Way
A formset is easier to trust once you have seen what it sends. Step 4 builds one from a two-line form, outside any page, and feeds it what a browser would send, and what a careless page would.
The Django Way
Step 1: Check the starting point
Terminal
uv run python manage.py test --parallel
Output
Found 399 test(s).
Creating test database for alias 'default'...
...
Ran 399 tests in ...s
OK
Terminal
git status --short
git log --oneline -1
Output
... Turn the editing pages into classes
Step 2: Pin the attendee list’s answers
The attendee list is still a function, and this chapter changes it, so by Chapter 37’s rule it becomes a class here, and ADR-006 rule 1 pins it first. It has login_required and no method check, so an organizer gets the list for every method, and anyone else gets 403, recorded. In registrations/tests/test_methods.py, import in_group:
registrations/tests/test_methods.py
from config.helpers import answers, in_group
and add at the end:
registrations/tests/test_methods.py
# The attendee list (Chapter 38), pinned while it is a
# function: sign-in first; then every method gets the list
# for the event's organizers, and 403, recorded, for anyone
# else.
ATTENDEES_ORGANIZER = [
(method, 'sign in', 'ok')
for method, _, _ in SIGNED_OUT_FIRST
]
ATTENDEES_OTHER = [
(method, 'sign in', '403 recorded')
for method, _, _ in SIGNED_OUT_FIRST
]
class AttendeesMethodTests(TestCase):
"""The attendee list's answer to each method, pinned."""
@classmethod
def setUpTestData(cls):
cls.event = soon()
cls.sam = in_group('sam@example.org', 'Organizers')
cls.event.add_organizer(cls.sam)
cls.sai = verified('sai@example.org')
def check(self, member, table):
"""Compare the list's answers with each row."""
path = url('attendees', self.event.pk)
for method, signed_out, signed_in in table:
with self.subTest(method):
self.assertEqual(
answers(path, member, method),
(signed_out, signed_in),
)
def test_for_an_organizer(self):
self.check(self.sam, ATTENDEES_ORGANIZER)
def test_for_anyone_else(self):
self.check(self.sai, ATTENDEES_OTHER)
Terminal
uv run python manage.py test registrations.tests.test_methods
Output
Found 6 test(s).
Creating test database for alias 'default'...
...
Ran 6 tests in ...s
OK
Step 3: Models and migrations
The member’s profile gains three facts. In accounts/models.py, after phone:
accounts/models.py
phone = PhoneNumberField(
blank=True,
help_text='Shown only to the organizers of events '
'you register for.',
)
# Facts an event may ask for (Chapter 38). Like the
# phone number, shown only to the organizers of events
# that ask for them and that you register for.
company = models.CharField(max_length=100, blank=True)
college = models.CharField(max_length=100, blank=True)
website = models.URLField(blank=True)
The event chooses which to ask for. In events/models.py, after phone_required, add:
events/models.py
asks_company = models.BooleanField(
'ask for their company', default=False
)
asks_college = models.BooleanField(
'ask for their college', default=False
)
asks_website = models.BooleanField(
'ask for their website', default=False
)
Registering needs to know whether anything is still owed. Add a reason to REASONS, and the list of facts, at the end of the dictionary:
events/models.py
'busy': 'Otahque is busy. Please try again.',
'answers_needed': 'This event asks a few questions '
'first.',
}
# Profile facts an event may ask for (Chapter 38).
FACTS = ['company', 'college', 'website']
a helper above moved():
events/models.py
def fact_of(member, name):
"""Return one of member's profile facts, or ''."""
profile = getattr(member, 'profile', None)
return getattr(profile, name) if profile else ''
and replace registration_problems() with three methods:
events/models.py
def registration_problems(self, member, now,
answers=None):
"""List, by code, why member cannot register now.
An empty list means member may register. answers
are the event's own questions, answered on the
details page; None means not asked yet.
"""
if self.place_of(member):
return ['already_registered']
problems = self.open_problems(now)
if not has_verified_email(member, member.email):
problems.append('unverified')
if self.phone_required and not phone_of(member):
problems.append('phone_missing')
if self.needs_answers(member, answers):
problems.append('answers_needed')
return problems
def asked_facts(self):
"""Return the profile facts this event asks for."""
return [name for name in FACTS
if getattr(self, f'asks_{name}')]
def needs_answers(self, member, answers):
"""Whether member still owes this event an answer.
A fact the event asks for must be on the profile;
each required question needs an answer. Questions
are read here, under the register() lock, so one
added a moment ago counts.
"""
if any(not fact_of(member, name)
for name in self.asked_facts()):
return True
questions = self.questions.filter(archived=False)
if answers is None:
return questions.exists()
required = questions.filter(required=True)
return any(f'q_{pk}' not in answers
for pk in required.values_list('pk',
flat=True))
registration_problems() takes the answers, or None when the member has not been asked yet; needs_answers() says whether anything is still owed: a fact the profile lacks, or, once answers are given, a required question without one. Because register() calls it after locking the event row, a question Sam adds while Sai is typing is counted. Replace register():
events/models.py
def register(self, member, now, answers=None):
"""Give member a place, or raise ValidationError.
The event row is locked first, so requests for it
take turns, and every check reads the locked row,
not this copy, which may be out of date. The unique
rule is still the backstop for the same member.
The answers are saved with the place, or neither is.
"""
with transaction.atomic():
event = self.locked()
problems = event.registration_problems(
member, now, answers
)
if problems:
raise refusal(problems)
try:
with transaction.atomic():
return event.registrations.create(
member=member, registered_at=now,
answers=answers or {},
)
except IntegrityError:
# Only the one-active-place rule means a
# repeat; any other failure is re-raised.
if event.place_of(member) is None:
raise
raise refusal(['already_registered'])
The answers are saved with the place, in the same create(), so there is never a place without its answers or answers without a place. Two more methods follow the questions: delete_draft() deletes a draft’s questions with it,
events/models.py
def delete_draft(self):
"""Delete a draft nobody registered for."""
if self.status != self.Status.DRAFT:
raise ValidationError(
'Only a draft can be deleted.'
)
if self.registrations.exists():
raise ValidationError(
'This draft has registrations, so it '
'is kept.'
)
with transaction.atomic():
self.organizer_assignments.all().delete()
self.questions.all().delete()
self.delete()
and copy_as_draft() copies the facts asked for and the questions still asked, each saved as a new row of the copy:
events/models.py
def copy_as_draft(self, member, starts_at):
"""Return a new draft with this event's details.
It starts at starts_at, organized by member; its
registration times move with the start.
"""
shift = starts_at - self.starts_at
with transaction.atomic():
copy = Event.objects.create(
title=self.title,
description=self.description,
timezone=self.timezone,
location=self.location,
capacity=self.capacity,
phone_required=self.phone_required,
asks_company=self.asks_company,
asks_college=self.asks_college,
asks_website=self.asks_website,
starts_at=starts_at,
ends_at=self.ends_at + shift,
registration_opens_at=moved(
self.registration_opens_at, shift),
registration_closes_at=moved(
self.registration_closes_at, shift),
cancellation_deadline=moved(
self.cancellation_deadline, shift),
)
copy.add_organizer(member)
for question in self.questions.filter(
archived=False):
question.pk = None
question.event = copy
question.save()
return copy
Setting question.pk = None and saving makes a new row with the same values, the standard way to copy a model instance.
Now registrations/models.py. The place keeps its answers; after cancelled_at:
registrations/models.py
cancelled_at = models.DateTimeField(
null=True, blank=True
)
# The event's own questions, answered when registering
# (Chapter 38): {q_<id>: value}.
answers = models.JSONField(default=dict, blank=True)
default=dict gives each new place its own empty dictionary; default={} would share one dictionary between them. My registrations will need to know whether a place’s event asks anything. Add a method to RegistrationQuerySet, above with_people():
Exists() with OuterRef('event') adds a true-or-false column computed by a subquery in the same SQL statement, so the list does not ask once per place. And the question itself, at the end of the file:
registrations/models.py
class RegistrationQuestion(models.Model):
"""One question an event asks when members register.
Removing a question archives it: its answers are kept,
and it is no longer asked (Chapter 38, D38.3).
"""
class Kind(models.TextChoices):
"""How a question is answered."""
SHORT = 'short', 'Short text'
LONG = 'long', 'Long text'
SINGLE = 'single', 'One choice'
SEVERAL = 'several', 'Several choices'
YES_NO = 'yes_no', 'Yes or no'
NUMBER = 'number', 'Number'
LINK = 'link', 'Link'
AGREEMENT = 'agreement', 'Agreement (must tick)'
event = models.ForeignKey(
'events.Event',
on_delete=models.PROTECT,
related_name='questions',
)
label = models.CharField(max_length=200)
help_text = models.CharField(max_length=300, blank=True)
kind = models.CharField(max_length=20, choices=Kind,
default=Kind.SHORT)
required = models.BooleanField(default=False)
choices = models.TextField(
blank=True, help_text='One choice on each line.'
)
position = models.PositiveSmallIntegerField(default=0)
archived = models.BooleanField(default=False)
added_at = models.DateTimeField(default=timezone.now)
class Meta:
ordering = ['position', 'id']
def __str__(self):
return self.label
@property
def key(self):
"""Name the answer and the form field: q_<id>.
A key that is only digits would be read by JSON
lookups as a position in a list, not a name.
"""
return f'q_{self.pk}'
def choice_list(self):
"""Return the choices, one per non-empty line."""
return [line.strip() for line
in self.choices.splitlines() if line.strip()]
Kind lists the eight kinds (D38.2, D38.7, D38.8). The event key is PROTECT, as every key has been since Chapter 20: an event with questions cannot be deleted by accident; delete_draft() deletes them on purpose. added_at lets a later question be optional for those who registered before it. key is the name of the answer and the form field. Changing answers is a new kind of attempt to record, so in audit/models.py, add an action after CANCEL_REGISTRATION:
Make the migrations, named, and read the one for questions:
Terminal
uv run python manage.py makemigrations -n profile_facts accounts
uv run python manage.py makemigrations -n asks events
uv run python manage.py makemigrations -n questions registrations
uv run python manage.py makemigrations -n change_answers audit
Output
Migrations for 'accounts':
accounts\migrations\0006_profile_facts.py
+ Add field college to profile
+ Add field company to profile
+ Add field website to profile
Migrations for 'events':
events\migrations\0009_asks.py
+ Add field asks_college to event
+ Add field asks_company to event
+ Add field asks_website to event
Migrations for 'registrations':
registrations\migrations\0004_questions.py
+ Add field answers to registration
+ Create model RegistrationQuestion
Migrations for 'audit':
audit\migrations\0003_change_answers.py
~ Alter field action on auditevent
Terminal
uv run python manage.py sqlmigrate registrations 0004
Output
BEGIN;
--
-- Add field answers to registration
--
ALTER TABLE "registrations_registration" ADD COLUMN "answers"
jsonb DEFAULT '{}'::jsonb NOT NULL;
ALTER TABLE "registrations_registration" ALTER COLUMN
"answers" DROP DEFAULT;
--
-- Create model RegistrationQuestion
--
CREATE TABLE "registrations_registrationquestion" ("id"
bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS
IDENTITY, "label" varchar(200) NOT NULL, "help_text"
varchar(300) NOT NULL, "kind" varchar(20) NOT NULL,
"required" boolean NOT NULL, "choices" text NOT NULL,
"position" smallint NOT NULL CHECK ("position" >= 0),
"archived" boolean NOT NULL, "added_at" timestamp with
time zone NOT NULL, "event_id" bigint NOT NULL);
ALTER TABLE "registrations_registrationquestion" ADD
CONSTRAINT
"registrations_regist_event_id_5055329e_fk_events_ev"
FOREIGN KEY ("event_id") REFERENCES "events_event" ("id")
DEFERRABLE INITIALLY DEFERRED;
CREATE INDEX
"registrations_registrationquestion_event_id_5055329e" ON
"registrations_registrationquestion" ("event_id");
COMMIT;
answers is jsonb on PostgreSQL, a binary JSON type the database can index and search. The DEFAULT '{}' fills in the places that already exist, then is dropped: from now on Django’s default=dict gives each new place its empty dictionary. Apply them:
Terminal
uv run python manage.py migrate
Output
Operations to perform:
Apply all migrations: account, accounts, admin, audit,
auth, contenttypes, events, mfa, registrations, sessions,
socialaccount
Running migrations:
Applying accounts.0006_profile_facts... OK
Applying audit.0003_change_answers... OK
Applying events.0009_asks... OK
Applying registrations.0004_questions... OK
Step 4: The Custom Way: a formset in plain Python
Create practice_formset.py beside manage.py:
practice_formset.py
"""Practice: a formset of a tiny form, outside any page.
Run it once, then delete it.
"""
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'config.settings')
django.setup()
from django import forms # noqa: E402
class SizeForm(forms.Form):
size = forms.CharField()
Sizes = forms.formset_factory(SizeForm, extra=2, max_num=3,
validate_max=True)
print([name for name in Sizes().management_form.fields])
print(Sizes(prefix='sizes').forms[1]['size'].html_name)
sent = {'sizes-TOTAL_FORMS': '2', 'sizes-INITIAL_FORMS': '0',
'sizes-0-size': 'M', 'sizes-1-size': 'L'}
both = Sizes(sent, prefix='sizes')
print(both.is_valid(), [f.cleaned_data for f in both])
four = sent | {'sizes-TOTAL_FORMS': '4',
'sizes-2-size': 'S', 'sizes-3-size': 'XL'}
print(Sizes(four, prefix='sizes').non_form_errors())
missing = Sizes({'sizes-0-size': 'M'}, prefix='sizes')
print(missing.is_valid(), missing.non_form_errors()[0][:56])
Terminal
uv run python practice_formset.py
Output
['TOTAL_FORMS', 'INITIAL_FORMS', 'MIN_NUM_FORMS',
'MAX_NUM_FORMS']
sizes-1-size
True [{'size': 'M'}, {'size': 'L'}]
<ul class="errorlist nonform"><li>Please submit at most 3
forms.</li></ul>
False ManagementForm data is missing or has been tampered
with
The first line is the management form’s four fields. The second shows the name the second copy’s field gets on the page: prefix, number, field. Two filled copies are valid, and cleaned_data comes per copy. Four copies against a limit of three fail as a whole, with an error that belongs to the formset, not to any one copy. And copies without a management form fail too: the formset does not know how many to read. Delete the file.
Step 5: The question builder’s forms
Replace registrations/forms.py. Its imports already include what Step 7 adds at the end:
registrations/forms.py
"""The registrations app's forms."""
from django import forms
from django.core.validators import URLValidator
from django.forms.models import (
BaseInlineFormSet, inlineformset_factory,
)
from phonenumber_field.formfields import PhoneNumberField
from accounts.forms import PHONE_HELP
from accounts.models import Profile
from events.forms import PartsForm
from events.models import Event
from .models import Registration, RegistrationQuestion
Kind = RegistrationQuestion.Kind
CHOICE_KINDS = (Kind.SINGLE, Kind.SEVERAL)
# Answers are short; a long one is refused (D38.5).
ANSWER_LIMIT = 500
WEB_ONLY = URLValidator(schemes=['http', 'https'])
class MyPlacesForm(PartsForm):
"""My registrations' filters (Chapter 36)."""
def __init__(self, *args, **kwargs):
"""Name My registrations' parts."""
super().__init__(*args, **kwargs)
self.fields['show'].choices = [
('registered', 'Registered'),
('cancelled', 'Cancelled'),
('past', 'Past'),
]
def answered_choices(question):
"""Return the choices someone has already chosen."""
key = question.key
chosen = set()
for answers in Registration.objects.filter(
event=question.event_id
).values_list('answers', flat=True):
value = answers.get(key)
if isinstance(value, str):
chosen.add(value)
elif isinstance(value, list):
chosen.update(value)
return chosen
class QuestionForm(forms.ModelForm):
"""One question in an event's question builder."""
class Meta:
model = RegistrationQuestion
fields = ['label', 'kind', 'choices', 'help_text',
'required']
labels = {'label': 'Question',
'help_text': 'Hint for members'}
widgets = {
'choices': forms.Textarea(attrs={'rows': 3}),
}
def clean(self):
"""Check the choices; an agreement is required."""
cleaned = super().clean()
kind = cleaned.get('kind')
lines = [line.strip() for line
in cleaned.get('choices', '').splitlines()
if line.strip()]
if kind in CHOICE_KINDS and len(lines) < 2:
self.add_error('choices', 'Give at least two '
'choices, one on each line.')
if kind == Kind.AGREEMENT:
cleaned['required'] = True
if self.instance.pk and kind in CHOICE_KINDS:
kept = set(lines)
for gone in sorted(answered_choices(self.instance)
- kept):
self.add_error('choices', f'"{gone}" has '
'answers, so it stays. To '
'change it, remove this '
'question and add a new one.')
return cleaned
class BaseQuestionFormSet(BaseInlineFormSet):
"""An event's questions, in order; removing archives.
Archived questions are not shown and do not count
towards the ten allowed.
"""
def __init__(self, *args, **kwargs):
"""Show only questions still asked."""
kwargs.setdefault(
'queryset',
RegistrationQuestion.objects.filter(archived=False),
)
super().__init__(*args, **kwargs)
def add_fields(self, form, index):
"""Say what removing a question does."""
super().add_fields(form, index)
if 'DELETE' in form.fields:
form.fields['DELETE'].label = (
'Remove (its answers are kept)'
)
def delete_existing(self, obj, commit=True):
"""Archive a removed question; keep its answers."""
obj.archived = True
if commit:
obj.save(update_fields=['archived'])
def save(self, commit=True):
"""Save, then number the questions in page order."""
saved = super().save(commit)
kept = [form.instance for form in self.forms
if form.instance.pk
and form not in self.deleted_forms]
for position, question in enumerate(kept):
if question.position != position:
question.position = position
question.save(update_fields=['position'])
return saved
QuestionFormSet = inlineformset_factory(
Event, RegistrationQuestion, form=QuestionForm,
formset=BaseQuestionFormSet, extra=1, can_delete=True,
max_num=10, validate_max=True,
)
QuestionForm is a model form for one question. Its clean() asks for at least two choices for the two choice kinds, makes an agreement always required, and refuses to drop a choice someone has chosen; answered_choices() reads the event’s places’ answers for this question’s key. BaseQuestionFormSet adds the chapter’s rules to Django’s inline formset. Its queryset leaves out archived questions, so they are not shown and do not count towards the ten. delete_existing() is the method Django calls for a ticked “Remove” box; here it archives instead. save() numbers the questions in the order the page shows them. QuestionFormSet puts it together: extra=1 adds one empty card for a new question, and max_num=10 with validate_max=True refuses an eleventh (D38.5).
Step 6: The builder on the edit page
The event form offers the three facts. In events/forms.py, EventForm’s fields read:
from audit.models import AuditEvent, record
from registrations.forms import QuestionFormSet
Chapter 33’s save_edit() saves the event under its lock. Now it saves the questions too, inside the same lock, the same version check, and the same transaction, as Figure 38.2 shows. Replace it:
events/views.py
def save_edit(request, event):
"""Save the edit form and the questions under the lock.
Return None once saved, or the form and the question
formset to show again. The lock makes the capacity
floor count the places taken now; the version shows
whether anyone saved the event after this page was
opened. Event and questions are saved together, or
neither is (Chapter 38).
"""
with transaction.atomic():
event = event.locked()
seen = VersionForm(request.POST)
if (not seen.is_valid()
or seen.cleaned_data['version']
!= event.version):
messages.error(request, STALE)
return (EventForm(instance=event),
QuestionFormSet(instance=event))
before = model_to_dict(event)
form = EventForm(request.POST, instance=event)
questions = QuestionFormSet(request.POST,
instance=event)
valid = form.is_valid()
if not (questions.is_valid() and valid):
return form, questions
event.version += 1
form.save()
questions.save()
after = model_to_dict(event)
changed = [name for name in form.fields
if before[name] != after[name]]
if questions.has_changed():
changed.append('questions')
record(request.user, Action.EDIT_EVENT, event,
fields=changed)
return None
valid = form.is_valid() runs first and on its own line, so that both the form and the formset are checked and both show their errors, even when the first fails. A change to the questions alone still adds one to the version and names “questions” in the record. Replace EventUpdateView with:
events/views.py
class EventUpdateView(LoginRequiredMixin, ManageEventMixin,
UpdateView):
"""Edit the event, for those who may change it.
GET is UpdateView's own. post() keeps save_edit(), so
the form is checked on the locked row (Chapter 33).
"""
form_class = EventForm
template_name = 'events/edit.html'
manage_action = Action.EDIT_EVENT
http_method_names = ['get', 'post']
def get_object(self, queryset=None):
"""Fetch the event; keep its title for the page."""
event = super().get_object(queryset)
self.title = event.title
return event
def post(self, request, *args, **kwargs):
"""Save under the lock, or show the forms again."""
self.object = self.get_object()
try:
shown = save_edit(request, self.object)
except ValidationError as error:
refuse(request, error)
shown = (EventForm(request.POST,
instance=self.object),
QuestionFormSet(request.POST,
instance=self.object))
if shown is None:
messages.success(request, 'Changes saved.')
return redirect(self.object)
form, questions = shown
return self.render_to_response(self.get_context_data(
form=form, questions=questions,
))
def get_context_data(self, **kwargs):
"""Add the title, places taken, and the questions."""
kwargs.setdefault(
'questions', QuestionFormSet(instance=self.object)
)
return super().get_context_data(**kwargs) | {
'title': self.title,
'taken': self.object.places_taken(),
}
Figure 38.2 — One POST saves the event and its questions together.
events/templates/events/event_fields.html gains the three boxes in its Registration group; the whole file now reads:
Create events/templates/events/questions.html, the builder:
events/templates/events/questions.html
<fieldset class="form-section">
<legend>Questions for people who register</legend>
<p class="text-sm">Up to ten, answered when members
register. Ask only what you need to run the event:
never health details, ID numbers, or passwords, and an
age range rather than a date of birth.</p>
{{ questions.management_form }}
{{ questions.non_form_errors }}
<ol class="question-cards">
{% for question in questions %}
<li class="question-card">
{% for hidden in question.hidden_fields %}
{{ hidden }}
{% endfor %}
{{ question.non_field_errors }}
<div class="form-grid">
{{ question.label.as_field_group }}
{{ question.kind.as_field_group }}
{{ question.choices.as_field_group }}
{{ question.help_text.as_field_group }}
{{ question.required.as_field_group }}
{% if question.instance.pk %}
{{ question.DELETE.as_field_group }}
{% endif %}
</div>
</li>
{% endfor %}
</ol>
</fieldset>
{{ questions.management_form }} is the line a formset cannot live without. Each card renders the copy’s hidden fields, id and the event, then its visible ones; “Remove” appears only on saved questions. In events/templates/events/edit.html, include it after the event’s fields:
events/templates/events/edit.html
{% include "events/event_fields.html" %}
{% include "events/questions.html" %}
Every test that posts the edit page builds its data with as_sent() in config/helpers.py. Now the page sends a management form, so the helper must too:
config/helpers.py
# The version the page was opened at (Chapter 33).
data['version'] = event.version
# The question builder's management form, with no
# questions sent (Chapter 38).
data['questions-TOTAL_FORMS'] = 0
data['questions-INITIAL_FORMS'] = 0
Write the builder’s tests. Create registrations/tests/test_questions.py:
registrations/tests/test_questions.py
"""Per-event registration questions (Chapter 38)."""
from datetime import timedelta
from django.test import TestCase
from django.utils import timezone
from accounts.models import Profile, User
from audit.models import AuditEvent
from config.helpers import admin_url, as_sent, in_group
from events.models import Event
from registrations.models import Registration
from registrations.models import RegistrationQuestion as Question
from .test_registrations import soon, url, verified
Kind = Question.Kind
def builder(event, *rows, initial=()):
"""Return what the edit page sends, with questions.
rows are dictionaries of a question's fields; initial
lists the questions already saved, sent first.
"""
sent = list(initial) + list(rows)
data = as_sent(event) | {
'questions-TOTAL_FORMS': len(sent),
'questions-INITIAL_FORMS': len(initial),
}
for n, row in enumerate(sent):
if isinstance(row, Question):
row = {'id': row.pk, 'label': row.label,
'kind': row.kind, 'choices': row.choices,
'required': row.required}
for name, value in row.items():
if value is True:
value = 'on'
if value is not False:
data[f'questions-{n}-{name}'] = value
return data
def ask(event, label, kind=Kind.SHORT, **fields):
"""Save one question on event."""
return Question.objects.create(event=event, label=label,
kind=kind, **fields)
class BuilderTests(TestCase):
"""Sam adds, changes, and removes his questions."""
@classmethod
def setUpTestData(cls):
cls.sam = in_group('sam@example.org', 'Organizers')
cls.event = soon()
cls.event.add_organizer(cls.sam)
def setUp(self):
self.client.force_login(self.sam)
self.edit = f'/events/{self.event.pk}/edit/'
def test_a_question_is_saved_with_the_event(self):
version = self.event.version
response = self.client.post(self.edit, builder(
self.event, {'label': 'Python level',
'kind': Kind.SINGLE,
'choices': 'New\nSome\nLots',
'required': True}))
self.assertRedirects(response,
self.event.get_absolute_url())
question = self.event.questions.get()
self.assertEqual(question.choice_list(),
['New', 'Some', 'Lots'])
self.event.refresh_from_db()
self.assertEqual(self.event.version, version + 1)
def test_bad_rows_save_nothing(self):
for row, error in [
({'kind': Kind.LONG}, 'This field is required'),
({'label': 'Size', 'kind': Kind.SINGLE,
'choices': 'M'}, 'at least two choices')]:
with self.subTest(error):
response = self.client.post(
self.edit, builder(self.event, row))
self.assertContains(response, error)
self.assertFalse(Question.objects.exists())
def test_an_eleventh_question_is_refused(self):
rows = [{'label': f'Q{n}', 'kind': Kind.SHORT}
for n in range(11)]
response = self.client.post(
self.edit, builder(self.event, *rows))
self.assertContains(response, 'at most 10')
self.assertFalse(Question.objects.exists())
def test_a_missing_management_form_saves_nothing(self):
data = builder(self.event)
del data['questions-TOTAL_FORMS']
response = self.client.post(self.edit, data)
self.assertContains(response, 'ManagementForm data')
before = self.event.version
self.event.refresh_from_db()
self.assertEqual(self.event.version, before)
def test_another_events_question_is_left_alone(self):
other = soon(title='Raj meetup')
theirs = ask(other, 'Team name')
row = {'id': theirs.pk, 'label': 'Changed',
'kind': Kind.SHORT}
data = builder(self.event) | {
'questions-TOTAL_FORMS': 1,
'questions-INITIAL_FORMS': 1,
} | {f'questions-0-{k}': v for k, v in row.items()}
self.client.post(self.edit, data)
theirs.refresh_from_db()
self.assertEqual(theirs.label, 'Team name')
self.assertEqual(theirs.event, other)
def test_a_stale_page_saves_no_question(self):
data = builder(self.event, {'label': 'Laptop?',
'kind': Kind.YES_NO})
self.event.version = 3
self.event.save(update_fields=['version'])
self.client.post(self.edit, data)
self.assertFalse(Question.objects.exists())
def test_removing_archives_and_keeps_answers(self):
question = ask(self.event, 'Laptop?', Kind.YES_NO)
sai = verified('sai@example.org')
place = self.event.register(
sai, timezone.now(), {question.key: 'yes'}
)
row = {'id': question.pk, 'label': 'Laptop?',
'kind': Kind.YES_NO, 'DELETE': True}
data = builder(self.event) | {
'questions-TOTAL_FORMS': 1,
'questions-INITIAL_FORMS': 1,
} | {f'questions-0-{k}': 'on' if v is True else v
for k, v in row.items()}
self.client.post(self.edit, data)
question.refresh_from_db()
self.assertTrue(question.archived)
place.refresh_from_db()
self.assertEqual(place.answers,
{question.key: 'yes'})
def test_an_answered_choice_stays(self):
question = ask(self.event, 'Size', Kind.SINGLE,
choices='S\nM\nL')
self.event.register(verified('sai@example.org'),
timezone.now(),
{question.key: 'M'})
question.choices = 'S\nL'
response = self.client.post(self.edit, builder(
self.event, initial=[question]))
self.assertContains(response, 'has answers, so it')
question.refresh_from_db()
self.assertEqual(question.choice_list(), ['S', 'M', 'L'])
builder() adds question rows to what the edit page sends, in the same questions-N-field names the page uses. The tests cover each rule in Step 5, the missing management form, a stale page, the tampered row from another event, archiving, and the answered choice. Run them:
Terminal
uv run python manage.py test registrations.tests.test_questions
Output
Found 8 test(s).
Creating test database for alias 'default'...
...
Ran 8 tests in ...s
OK
Then the events app, whose markup tests count the form’s fields:
Terminal
uv run python manage.py test events --parallel
Output
Found 215 test(s).
Creating test database for alias 'default'...
FAIL: test_fields_use_otahque_styles_and_script
AssertionError: 14 != 11 : Found 14 instances of
'class="fieldset"' (expected 11) in the following
response
FAIL: test_tick_box_is_styled_and_linked
AssertionError: 5 != 2 : Found 5 instances of
'class="checkbox"' (expected 2) in the following response
Ran 215 tests in ...s
FAILED (failures=2)
Both counts changed because the form has three more fields, which is intended. In events/tests/test_events.py:
events/tests/test_events.py
for text, count in (('class="fieldset"', 14),
events/tests/test_events.py
# Five tick boxes: the new zone, the phone setting,
# and the three facts to ask for (Chapter 38).
self.assertContains(response, 'class="checkbox"',
count=5)
Output
Found 215 test(s).
Creating test database for alias 'default'...
...
Ran 215 tests in ...s
OK
Step 7: A form built from the questions
Add the run-time form at the end of registrations/forms.py:
registrations/forms.py
def field_for(question):
"""Return the form field that asks question."""
common = {'label': question.label,
'help_text': question.help_text,
'required': question.required}
kind = question.kind
if kind == Kind.LONG:
return forms.CharField(widget=forms.Textarea(
attrs={'rows': 3}), max_length=ANSWER_LIMIT,
**common)
if kind == Kind.SINGLE:
return forms.ChoiceField(
choices=[(c, c) for c in question.choice_list()],
widget=forms.RadioSelect, **common)
if kind == Kind.SEVERAL:
return forms.MultipleChoiceField(
choices=[(c, c) for c in question.choice_list()],
widget=forms.CheckboxSelectMultiple, **common)
if kind == Kind.YES_NO:
return forms.ChoiceField(
choices=[('yes', 'Yes'), ('no', 'No')],
widget=forms.RadioSelect, **common)
if kind == Kind.NUMBER:
return forms.IntegerField(min_value=0, **common)
if kind == Kind.LINK:
return forms.URLField(
assume_scheme='https', validators=[WEB_ONLY],
max_length=ANSWER_LIMIT, **common)
if kind == Kind.AGREEMENT:
return forms.BooleanField(**common | {
'required': True})
return forms.CharField(max_length=ANSWER_LIMIT, **common)
FACT_FIELDS = {
'company': lambda: forms.CharField(
label='Company', max_length=100),
'college': lambda: forms.CharField(
label='College', max_length=100),
'website': lambda: forms.URLField(
label='Website', assume_scheme='https',
validators=[WEB_ONLY]),
}
class DetailsForm(forms.Form):
"""What an event asks before a member registers (38).
Built at run time: the phone number and profile facts
the event asks for, then one field per question, named
by its key, q_<id>, so a reworded question keeps its
answers. With
a registration, it is the form for changing answers:
no profile fields and no agreements, and a required
question added after registering is optional (D38.3).
"""
def __init__(self, *args, event, member,
registration=None, **kwargs):
"""Add the fields this event asks for."""
super().__init__(*args, **kwargs)
self.member = member
self.questions = list(
event.questions.filter(archived=False)
)
if registration is None:
self.ask_profile(event)
for question in self.questions:
field = field_for(question)
if registration is not None:
if question.kind == Kind.AGREEMENT:
continue
field.required = (
field.required and question.added_at
<= registration.registered_at
)
field.initial = registration.answers.get(
question.key
)
self.fields[question.key] = field
def ask_profile(self, event):
"""Add the phone and facts, filled from the profile.
Nothing is saved until the form is: a member who
has no Profile yet gets one in save_profile().
"""
profile = Profile.objects.filter(
user=self.member
).first() or Profile()
if event.phone_required:
self.fields['phone'] = PhoneNumberField(
label='Phone number', help_text=PHONE_HELP,
initial=profile.phone,
)
for name in event.asked_facts():
field = FACT_FIELDS[name]()
field.initial = getattr(profile, name)
self.fields[name] = field
def answers(self, now):
"""Return the answers to keep: {q_<id>: value}.
An agreement keeps the time it was ticked.
"""
kept = {}
for question in self.questions:
value = self.cleaned_data.get(question.key)
if value in (None, '', [], False):
continue
if question.kind == Kind.AGREEMENT:
value = {'agreed': True,
'at': now.isoformat()}
kept[question.key] = value
return kept
def save_profile(self):
"""Keep the phone number and facts on the profile."""
names = [name for name in self.fields
if not name.startswith('q_')]
if not names:
return
profile = Profile.of(self.member)
for name in names:
setattr(profile, name, self.cleaned_data[name])
profile.full_clean()
profile.save(update_fields=names)
# register() reads the member's profile next.
self.member.profile = profile
field_for() turns a question into a field, by kind, as Figure 38.3 shows. Text is limited to 500 characters (D38.5); a number is a whole number from zero; a link must be http or https, which WEB_ONLY checks, because URLField alone would accept ftp. DetailsForm.__init__() takes the event and the member as keyword arguments, so they cannot be confused with the submitted data. With a registration, the same form is the “change my answers” form: no profile fields, no agreements, the saved answers filled in, and a required question added after the member registered left optional. answers() returns only what was answered, keyed by q_<id>, and stores an agreement as the time it was ticked. save_profile() writes the phone and facts back to the profile, then puts that profile on the member, so register() reads the new values.
Figure 38.3 — A form built from an event’s questions.
Choices are drawn as radio buttons and tick boxes. Otahque’s input template gives every input the classes of a text box, so two small templates override the options Django draws for RadioSelect and CheckboxSelectMultiple. Create templates/django/forms/widgets/radio_option.html:
In registrations/views.py, the imports change: PhoneForm goes, DetailsForm arrives:
registrations/views.py
"""Pages for members' places and organizers' lists."""
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ValidationError
from django.shortcuts import (
get_object_or_404, redirect, render,
)
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views import View
from django.views.generic import (
DetailView, FormView, ListView,
)
from django.views.decorators.http import (
require_http_methods, require_POST,
)
from audit.models import AuditEvent
from events.models import REASONS, Event
from events.views import deny, page_numbers
from .forms import DetailsForm, MyPlacesForm
from .models import Registration
take_place() passes the answers on, and sends a member who still owes something to the details page:
registrations/views.py
def take_place(request, event, answers=None):
"""Register the member, then say what happened.
If the event still needs a phone number or answers,
the member is sent to the details page.
"""
try:
event.register(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'}:
return redirect('registrations:details',
event.pk)
if codes == ['already_registered']:
messages.info(request, REASONS['already_registered'])
else:
for message in error.messages:
messages.error(request, message)
else:
messages.success(request, 'You have a place.')
return redirect(event)
Replace RegistrationDetailsView; its decorators above it stay:
registrations/views.py
class RegistrationDetailsView(View):
"""Ask for what an event needs, then register.
The phone number and profile facts the event asks for,
then its own questions (Chapter 38). The list runs in
order, as the function's decorators did: the method
check, sign-in, then dispatch() loads the event.
"""
def dispatch(self, request, *args, **kwargs):
"""Load the event, then call get() or post()."""
self.event = event_for(request, kwargs['event_id'])
return super().dispatch(request, *args, **kwargs)
def get(self, request, event_id):
"""Show the empty form."""
return self.show(self.form())
def post(self, request, event_id):
"""Keep the details and take a place, or show errors."""
form = self.form(request.POST)
if form.is_valid():
form.save_profile()
return take_place(request, self.event,
form.answers(timezone.now()))
return self.show(form)
def form(self, data=None):
"""Return the form this event asks for."""
return DetailsForm(data, event=self.event,
member=self.request.user)
def show(self, form):
"""Render the page with the form."""
return render(
self.request, 'registrations/details.html',
{'event': self.event, 'form': form},
)
The page asks for more than a phone number now, so its address and name change (N38.11). In registrations/urls.py:
{% extends "base.html" %}
{% block title %}Your details | Otahque{% endblock %}
{% block content %}
<h1>{{ event.title }} asks for a few details</h1>
{% include "events/facts.html" %}
<p>Your phone number, company, college, and website are
kept on your profile, so you are asked only once. You
can change them there.</p>
{% include "registrations/sharing.html" %}
<form method="post" class="card max-w-xl space-y-4 border
border-base-300 bg-base-100 p-6">
{% csrf_token %}
{{ form }}
<button type="submit" class="btn btn-primary">
Save and register</button>
</form>
<p>
<a href="{{ event.get_absolute_url }}">Back to the
event</a>
</p>
{% endblock %}
The note under every Register button says what registering shares, registrations/templates/registrations/sharing.html:
<p class="text-sm">Registering shares your name, email
address, and phone number with this event's organizers,
and your answers to its questions.</p>
The event page’s panel sends a member to the details page whenever something is owed. In events/views.py, replace registration_panel():
events/views.py
def registration_panel(event, user, now):
"""Return what the event page says about registering."""
if not user.is_authenticated:
codes = event.open_problems(now)
return {'reasons': [REASONS[c] for c in codes]}
place = event.place_of(user)
codes = [] if place else event.registration_problems(
user, now
)
asks = {'phone_missing', 'answers_needed'}
return {
'place': place,
'reasons': [REASONS[c] for c in codes
if c not in asks],
'needs_details': bool(asks & set(codes)),
'unverified': 'unverified' in codes,
'can_see_attendees': event.can_see_attendees(user),
}
and in registrations/templates/registrations/panel.html, the link uses the new name; the whole file reads:
registrations/templates/registrations/panel.html
<section class="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">
Registration</h2>
{% if place %}
<p><span class="badge badge-success">You have a
place</span> Registered
{{ place.registered_at|date:"j M Y, H:i" }}.</p>
<p><a href="{% url 'registrations:cancel' place.pk %}">
Cancel my place</a></p>
{% 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 %}
<form method="post"
action="{% url 'registrations:register' event.pk %}">
{% csrf_token %}
<button type="submit" class="btn btn-primary">
Register</button>
</form>
{% include "registrations/sharing.html" %}
{% endif %}
{% if can_see_attendees %}
<p><a href="{% url 'registrations:attendees' event.pk %}">
Attendee list</a></p>
{% endif %}
</section>
Three tests in registrations/tests/test_registrations.py and two in registrations/tests/test_methods.py name the page phone; change url('phone', ...) and url("phone", ...) to details in both files. Add the registration tests at the end of registrations/tests/test_questions.py:
registrations/tests/test_questions.py
class RegisterTests(TestCase):
"""Sai answers the questions when she registers."""
@classmethod
def setUpTestData(cls):
cls.event = soon(asks_company=True)
cls.level = ask(cls.event, 'Python level', Kind.SINGLE,
choices='New\nSome', required=True)
cls.terms = ask(cls.event, 'I agree to the code of '
'conduct', Kind.AGREEMENT,
required=True)
cls.site = ask(cls.event, 'Your site', Kind.LINK)
ask(cls.event, 'Old question', archived=True)
cls.sai = verified('sai@example.org')
def setUp(self):
self.client.force_login(self.sai)
self.details = url('details', self.event.pk)
def sent(self, **changes):
data = {'company': 'Leeds Library',
f'q_{self.level.pk}': 'Some',
f'q_{self.terms.pk}': 'on'}
return data | changes
def test_register_sends_her_to_the_questions(self):
response = self.client.post(url('register',
self.event.pk))
self.assertRedirects(response, self.details)
page = self.client.get(self.details)
self.assertContains(page, 'Python level')
self.assertNotContains(page, 'Old question')
def test_place_answers_and_company_saved_together(self):
response = self.client.post(self.details, self.sent())
self.assertRedirects(response,
self.event.get_absolute_url(),
fetch_redirect_response=False)
place = Registration.objects.get()
self.assertEqual(place.answers[self.level.key],
'Some')
agreed = place.answers[self.terms.key]
self.assertTrue(agreed['agreed'])
self.assertIn('at', agreed)
self.assertEqual(Profile.of(self.sai).company,
'Leeds Library')
def test_refused_answers_make_no_place(self):
level, terms = f'q_{self.level.pk}', f'q_{self.terms.pk}'
for changes, error in [
({level: ''}, 'This field is required'),
({level: 'Expert'}, 'Select a valid choice'),
({terms: ''}, 'This field is required'),
({f'q_{self.site.pk}': 'ftp://x.org'},
'Enter a valid URL')]:
with self.subTest(error):
data = {k: v for k, v
in self.sent(**changes).items() if v}
response = self.client.post(self.details, data)
self.assertContains(response, error)
self.assertFalse(Registration.objects.exists())
def test_a_question_added_meanwhile_is_asked(self):
ask(self.event, 'T-shirt size', required=True)
response = self.client.post(self.details, self.sent())
self.assertContains(response, 'T-shirt size')
self.assertContains(response, 'This field is required')
self.assertFalse(Registration.objects.exists())
The last test adds a required question after Sai opened the page. Her form is built again when she posts, from the questions as they are now, so it shows the new question with “This field is required” and takes no place. If the question arrived between that check and register(), the lock-time check in needs_answers() would send her back. Run the questions tests, then the whole app:
Terminal
uv run python manage.py test registrations.tests.test_questions
Output
Found 12 test(s).
Creating test database for alias 'default'...
...
Ran 12 tests in ...s
OK
Terminal
uv run python manage.py test registrations --parallel
Output
Found 87 test(s).
Creating test database for alias 'default'...
...
Ran 87 tests in ...s
OK
Step 9: The attendee list, and changing answers
My registrations asks whether each place’s event has questions. In registrations/views.py, MyRegistrationsView.get_queryset() becomes:
registrations/views.py
def get_queryset(self):
"""Return this member's places, never anyone else's."""
return self.request.user.registrations.select_related(
'event'
).showing(
self.form.parts(), self.now
).in_list_order(self.now).with_questions()
Replace attendees with a helper, the change-answers page, and the attendee list as a class. First the helper and the new page:
registrations/views.py
def own_place(request, registration_id, action):
"""Return the member's own place, or 404, recorded."""
registration = get_object_or_404(
Registration.objects.select_related('event'),
pk=registration_id,
)
if registration.member_id != request.user.pk:
deny(request, action, registration, hidden=True)
return registration
class AnswersView(LoginRequiredMixin, FormView):
"""Change your answers to an event's questions.
Until the event starts; agreements are not changed
(Chapter 38, D38.5 and D38.8).
"""
template_name = 'registrations/answers.html'
http_method_names = ['get', 'post']
def dispatch(self, request, *args, **kwargs):
"""Refuse after the start, once signed in."""
if not request.user.is_authenticated:
return super().dispatch(request, *args, **kwargs)
self.place = own_place(request,
kwargs['registration_id'],
Action.CHANGE_ANSWERS)
if timezone.now() >= self.place.event.starts_at:
messages.error(request, 'The event has started, '
'so answers can no longer change.')
return redirect('registrations:mine')
return super().dispatch(request, *args, **kwargs)
def get_form(self, form_class=None):
"""Return the answers form, filled in."""
return DetailsForm(
**self.get_form_kwargs(), event=self.place.event,
member=self.request.user, registration=self.place,
)
def get_context_data(self, **kwargs):
"""Add the place and its event."""
return super().get_context_data(**kwargs) | {
'place': self.place,
'event': self.place.event,
}
def form_valid(self, form):
"""Keep the agreements; replace the other answers."""
agreed = {key: value for key, value
in self.place.answers.items()
if isinstance(value, dict)}
self.place.answers = agreed | form.answers(
timezone.now()
)
self.place.save(update_fields=['answers'])
messages.success(self.request, 'Answers saved.')
return redirect('registrations:mine')
own_place() is the cancel page’s rule as a function: a member’s own place, or 404, recorded. AnswersView.dispatch() checks it only once the member is signed in, so a visitor still goes to sign in first; then it refuses after the start. form_valid() keeps every agreement as it was and replaces the other answers. Then the list:
registrations/views.py
def shown(value):
"""Return one answer as the attendee list shows it."""
if isinstance(value, list):
return ', '.join(value)
if isinstance(value, dict):
return 'Agreed'
return '' if value is None else str(value)
class AttendeesView(LoginRequiredMixin, ListView):
"""The attendee list, for the event's organizers.
One column per profile fact the event asks for, and
one per question; archived questions keep their column.
"""
template_name = 'registrations/attendees.html'
context_object_name = 'places'
def get(self, request, *args, **kwargs):
"""Refuse anyone who may not see the list."""
event = get_object_or_404(Event, pk=kwargs['event_id'])
if not event.is_visible_to(request.user):
deny(request, Action.VIEW_ATTENDEES, event,
hidden=True)
if not event.can_see_attendees(request.user):
deny(request, Action.VIEW_ATTENDEES, event)
self.event = event
return super().get(request, *args, **kwargs)
def get_queryset(self):
"""Places held now, with each member and profile."""
return self.event.registrations.active().with_people()
def get_context_data(self, **kwargs):
"""Add the columns and a row of answers per place."""
context = super().get_context_data(**kwargs)
questions = list(self.event.questions.all())
facts = self.event.asked_facts()
rows = [
(place,
[getattr(place.member.profile, name)
for name in facts],
[shown(place.answers.get(question.key))
for question in questions])
for place in context['places']
]
return context | {
'event': self.event,
'facts': facts,
'questions': questions,
'rows': rows,
'counts': self.event.registrations
.cancellation_counts(),
}
AttendeesView checks access in get() before ListView does anything else. The rows are built in Python from what the queryset already fetched: the member, the profile, the place’s answers, and the event’s questions, read once. Archived questions keep their column, so answers given before a question was removed stay visible. registrations/urls.py now reads:
registrations/urls.py
"""Addresses of the registrations app's pages."""
from django.urls import path
from . import views
app_name = 'registrations'
urlpatterns = [
path('events/<int:event_id>/register/',
views.register, name='register'),
path('events/<int:event_id>/register/details/',
views.RegistrationDetailsView.as_view(),
name='details'),
path('registrations/',
views.MyRegistrationsView.as_view(),
name='mine'),
path('registrations/<int:registration_id>/cancel/',
views.CancelRegistrationView.as_view(),
name='cancel'),
path('events/<int:event_id>/registrations/',
views.AttendeesView.as_view(),
name='attendees'),
path('registrations/<int:registration_id>/answers/',
views.AnswersView.as_view(), name='answers'),
]
{% extends "base.html" %}
{% block title %}Attendees of {{ event.title }} |
Otahque{% endblock %}
{% block content %}
<h1>Attendees of {{ event.title }}</h1>
<p>{{ places|length }} of {{ event.capacity }} places
taken. Cancellations: {{ counts.cancelled }}, of
which late: {{ counts.late }}.</p>
<p class="text-sm">Contact details are for running this
event only. Do not copy them elsewhere.</p>
{% if places %}
<div class="table-card" role="region" tabindex="0"
aria-labelledby="attendees-caption">
<table class="table">
<caption id="attendees-caption" class="sr-only">
Attendees, with their answers</caption>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col">Phone</th>
<th scope="col">Registered</th>
{% for name in facts %}
<th scope="col">{{ name|capfirst }}</th>
{% endfor %}
{% for question in questions %}
<th scope="col">{{ question.label }}
{% if question.archived %}(removed){% endif %}
</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for place, fact_values, answers in rows %}
{% with person=place.member %}
<tr>
<td>{{ person.display_name }}</td>
<td>{{ person.email }}</td>
{% with phone=person.profile.phone %}
<td>
{{ phone.as_international|default:"Not given" }}
</td>
{% endwith %}
<td>{{ place.registered_at|date:"j M Y, H:i" }}
</td>
{% for value in fact_values %}
<td>{{ value }}</td>
{% endfor %}
{% for value in answers %}
<td>{{ value }}</td>
{% endfor %}
</tr>
{% endwith %}
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p>Nobody has a place yet.</p>
{% endif %}
<p>
<a href="{{ event.get_absolute_url }}">Back to the
event</a>
</p>
{% endblock %}
The table sits in a table-card, which scrolls sideways inside itself on a phone. A region that scrolls must be reachable by keyboard, so it has tabindex="0", a role, and a name from the table’s caption, which is hidden on screen with sr-only but read aloud. Create registrations/templates/registrations/answers.html:
The query-count test makes the list, then adds a question and a fourth attendee, and expects the same ten queries both times: two of them are the navigation’s permission check. Run the questions tests, then the tables:
Terminal
uv run python manage.py test registrations.tests.test_questions
Output
Found 18 test(s).
Creating test database for alias 'default'...
...
Ran 18 tests in ...s
OK
Terminal
uv run python manage.py test registrations.tests.test_methods
Output
Found 6 test(s).
Creating test database for alias 'default'...
FAIL: test_for_an_organizer [POST]
AssertionError: ('sign in', '405 GET, HEAD, OPTIONS') !=
('sign in', 'ok')
FAIL: test_for_an_organizer [PUT]
AssertionError: ('sign in', '405 GET, HEAD, OPTIONS') !=
('sign in', 'ok')
FAIL: test_for_an_organizer [PATCH]
AssertionError: ('sign in', '405 GET, HEAD, OPTIONS') !=
('sign in', 'ok')
... (9 more like these)
Ran 6 tests in ...s
FAILED (failures=12)
As a ListView, the attendee list answers 405 to methods other than GET and HEAD, and OPTIONS itself, while sign-in still comes first. For anyone who is not an organizer, GET and HEAD are still refused and recorded; other methods are refused by method, before the event is looked at. Declare it: replace the block you added in Step 2 with:
registrations/tests/test_methods.py
# The attendee list (Chapter 38), as a ListView: sign-in
# first; then GET and HEAD for the event's organizers, and
# 403, recorded, for anyone else.
ALLOW = 'GET, HEAD, OPTIONS'
ATTENDEES_OTHER = [
(method, 'sign in',
'403 recorded' if method in ('GET', 'HEAD')
else f'ok {ALLOW}' if method == 'OPTIONS'
else f'405 {ALLOW}')
for method, _, _ in SIGNED_OUT_FIRST
]
class AttendeesMethodTests(TestCase):
"""The attendee list's answer to each method, pinned."""
@classmethod
def setUpTestData(cls):
cls.event = soon()
cls.sam = in_group('sam@example.org', 'Organizers')
cls.event.add_organizer(cls.sam)
cls.sai = verified('sai@example.org')
def check(self, member, table):
"""Compare the list's answers with each row."""
path = url('attendees', self.event.pk)
for method, signed_out, signed_in in table:
with self.subTest(method):
self.assertEqual(
answers(path, member, method),
(signed_out, signed_in),
)
def test_for_an_organizer(self):
self.check(self.sam, SIGNED_OUT_FIRST)
def test_for_anyone_else(self):
self.check(self.sai, ATTENDEES_OTHER)
Output
Found 6 test(s).
Creating test database for alias 'default'...
...
Ran 6 tests in ...s
OK
Step 10: Copying an event’s questions
copy_as_draft() changed in Step 3. Prove it, at the end of registrations/tests/test_questions.py:
registrations/tests/test_questions.py
class CopyTests(TestCase):
"""A copy asks the same questions, and its own."""
def test_questions_are_copied_not_shared(self):
sam = in_group('sam@example.org', 'Organizers')
event = soon(asks_college=True)
ask(event, 'Python level', position=0)
ask(event, 'Old one', archived=True)
copy = event.copy_as_draft(
sam, event.starts_at + timedelta(days=7))
self.assertTrue(copy.asks_college)
self.assertEqual(
[q.label for q in copy.questions.all()],
['Python level'],
)
self.assertEqual(event.questions.count(), 2)
Terminal
uv run python manage.py test registrations.tests.test_questions
Output
Found 19 test(s).
Creating test database for alias 'default'...
...
Ran 19 tests in ...s
OK
The copy asks what the original asks now: the facts, and the questions still asked, as new rows of its own. An archived question stays behind, and the original keeps both of its own.
Step 11: The admin
Soni, the administrator, picks organizers from a dropdown of every member, scrolls through every event ever held, and cannot see an event’s questions. In events/admin.py, the top of the file, up to EventAdminForm, becomes:
events/admin.py
"""Admin pages for events and their organizers."""
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from django import forms
from django.contrib import admin, messages
from django.core.exceptions import ValidationError
from django.utils import timezone
from audit.models import AuditEvent, record
from registrations.models import (
Registration, RegistrationQuestion,
)
from .models import (
Event, OrganizerAssignment, organizer_problem,
)
UTC_HELP = "In UTC, not the event's own time zone."
class RegistrationInline(admin.TabularInline):
"""An event's registrations, shown as history."""
model = Registration
fields = ['member', 'status', 'registered_at',
'cancelled_at']
readonly_fields = fields
extra = 0
can_delete = False
def has_add_permission(self, request, obj=None):
"""Members register on the site, not here."""
return False
def has_change_permission(self, request, obj=None):
"""Registrations are history: never edited."""
return False
def get_queryset(self, request):
"""Fetch each registration's member at once."""
queryset = super().get_queryset(request)
return queryset.select_related('member')
class QuestionInline(admin.TabularInline):
"""An event's questions, for the administrator to read.
Organizers change them on the site's edit page.
"""
model = RegistrationQuestion
fields = ['label', 'kind', 'required', 'archived']
readonly_fields = fields
extra = 0
can_delete = False
def has_add_permission(self, request, obj=None):
"""Questions are added on the site, not here."""
return False
def has_change_permission(self, request, obj=None):
"""Read-only here."""
return False
class WhenFilter(admin.SimpleListFilter):
"""Upcoming or past, by the end time, as on the site."""
title = 'when'
parameter_name = 'when'
def lookups(self, request, model_admin):
"""Offer the two choices."""
return [('upcoming', 'Not yet ended'),
('past', 'Ended')]
def queryset(self, request, queryset):
"""Narrow the list to the choice, if any."""
now = timezone.now()
if self.value() == 'upcoming':
return queryset.filter(ends_at__gt=now)
if self.value() == 'past':
return queryset.filter(ends_at__lte=now)
return queryset
QuestionInline shows an event’s questions, read-only: organizers change them on the site. WhenFilter is a custom list filter, Upcoming or Past by the end time, as the site’s list decides it. EventAdmin’s settings, up to get_queryset():
date_hierarchy adds year, month, and day links above the list. OrganizerAssignmentAdmin gains search boxes instead of dropdowns:
events/admin.py
class OrganizerAssignmentAdmin(admin.ModelAdmin):
"""Assign organizers; revoke, but never delete."""
list_display = ['event', 'member', 'assigned_at',
'revoked_at']
list_filter = [
('revoked_at', admin.EmptyFieldListFilter),
]
list_select_related = ['event', 'member']
autocomplete_fields = ['event', 'member']
form = AssignmentForm
actions = ['remove_selected']
autocomplete_fields needs the related models’ admins to have search_fields, which EventAdmin and UserAdmin already have. In config/urls.py, the admin’s browser tab and front page get Otahque’s words:
config/urls.py
admin.site.site_header = 'Otahque administration'
admin.site.site_title = 'Otahque admin'
admin.site.index_title = 'Community data'
admin.site.site_title = 'Otahque admin'
# Staff sign in through allauth's page, with its limits and
# two-factor sign-in; the admin's own form is never used.
admin.site.login = secure_admin_login(admin.site.login)
The admin’s event page now sends the questions inline’s management form too, so event_form() in config/helpers.py does:
The first test signs in as a superuser, who holds every permission. Soni is not one: she is a member of the Administrators group from Chapter 30, and the group has no permission for RegistrationQuestion, a model that did not exist then. The admin shows an inline only to someone who may view its model, so on her screen the questions are simply missing, with no error. The second test signs in as Soni, and without a change it fails.
A group’s permissions are data, so a data migration changes them, as accounts/migrations/0004_groups.py created them. Create the file registrations/migrations/0005_administrators.py by hand; makemigrations writes only migrations for changed models:
registrations/migrations/0005_administrators.py
"""Administrators read each event's questions (Chapter 38)."""
from django.contrib.auth.management import create_permissions
from django.db import migrations
APP, CODENAME = 'registrations', 'view_registrationquestion'
def grant(apps, schema_editor):
"""Let Administrators read each event's questions."""
# A new model's permissions are made after the last
# migration, so a new database has none yet: make
# them first, as accounts/0004_groups does.
config = apps.get_app_config(APP)
config.models_module = True
create_permissions(config, apps=apps, verbosity=0)
config.models_module = None
Group = apps.get_model('auth', 'Group')
Permission = apps.get_model('auth', 'Permission')
group = Group.objects.filter(name='Administrators')
if group.exists():
group.get().permissions.add(Permission.objects.get(
content_type__app_label=APP, codename=CODENAME,
))
def revoke(apps, schema_editor):
"""Take the permission away again."""
Group = apps.get_model('auth', 'Group')
for group in Group.objects.filter(name='Administrators'):
group.permissions.remove(*group.permissions.filter(
content_type__app_label=APP, codename=CODENAME,
))
class Migration(migrations.Migration):
dependencies = [
('accounts', '0006_profile_facts'),
('registrations', '0004_questions'),
]
operations = [
migrations.RunPython(grant, revoke),
]
Common Error: the permission does not exist yet
Django creates a model’s permissions after the last migration has run, in a post_migrate handler. On your database, which migrated in Step 3, view_registrationquestion exists already. On a new database, such as the one every test run creates, it does not exist yet when this migration runs, and Permission.objects.get() raises DoesNotExist. grant() therefore calls create_permissions() first, which makes any missing permissions and leaves existing ones alone.
Chapter 30’s group test pins each group’s permissions exactly, so it changes too, on purpose. In accounts/tests/test_accounts.py:
accounts/tests/test_accounts.py
# Chapter 30: the two groups the migration creates.
GROUPS = {
'Administrators': [
'accounts.change_user', 'accounts.view_user',
'admin.view_logentry', 'audit.view_auditevent',
'events.change_event',
'events.add_organizerassignment',
'events.change_organizerassignment',
'events.view_organizerassignment',
'events.delete_event', 'events.manage_organizers',
'events.view_event',
'registrations.view_registration',
# Chapter 38: each event's questions, in the admin.
'registrations.view_registrationquestion',
],
'Organizers': [
'events.add_event', 'events.change_event',
],
}
Terminal
uv run python manage.py migrate
Output
Operations to perform:
Apply all migrations: account, accounts, admin, audit,
auth, contenttypes, events, mfa, registrations, sessions,
socialaccount
Running migrations:
Applying registrations.0005_administrators... OK
Terminal
uv run python manage.py test registrations.tests.test_questions
Output
Found 22 test(s).
Creating test database for alias 'default'...
...
Ran 22 tests in ...s
OK
Terminal
uv run python manage.py test accounts --parallel
Output
Found 86 test(s).
Creating test database for alias 'default'...
...
Ran 86 tests in ...s
OK
Step 12: Profile, cards, records, and commit
The details page says the facts can be changed on the profile, so the profile must offer them. In accounts/forms.py, ProfileForm gains three fields, and PhoneForm, which nothing uses any more, goes:
accounts/forms.py
class ProfileForm(forms.Form):
"""The member's name, zone, phone, and facts."""
display_name = forms.CharField(
max_length=100, help_text=NAME_HELP,
)
timezone = forms.ChoiceField(
choices=ZONE_CHOICES, required=False,
label='Time zone (optional)',
)
phone = PhoneNumberField(
required=False, label='Phone number (optional)',
help_text=PHONE_HELP,
)
# Facts an event may ask for (Chapter 38).
company = forms.CharField(
max_length=100, required=False,
label='Company (optional)',
)
college = forms.CharField(
max_length=100, required=False,
label='College (optional)',
)
website = forms.URLField(
required=False, label='Website (optional)',
assume_scheme='https',
)
def save(self, user):
"""Save the name to the user, the rest to Profile."""
user.display_name = self.cleaned_data['display_name']
user.save(update_fields=['display_name'])
profile = Profile.of(user)
for name in ('timezone', 'phone', 'company',
'college', 'website'):
setattr(profile, name, self.cleaned_data[name])
profile.full_clean()
profile.save()
In accounts/views.py, ProfileView fills them in:
accounts/views.py
def get_initial(self):
"""Fill the form from the member and their profile."""
user = self.request.user
profile = Profile.of(user)
return {
'display_name': user.display_name,
'timezone': profile.timezone,
'phone': profile.phone,
'company': profile.company,
'college': profile.college,
'website': profile.website,
}
The styles, in static/otahque/source.css, inside @layer components, above .form-actions:
static/otahque/source.css
/* Questions (Chapter 38): each one a card; the
attendee table scrolls sideways inside its own card,
not the page. */
.question-cards {
display: grid;
gap: 0.75rem;
}
.question-card {
padding: 1rem;
border: 1px solid var(--color-base-300);
border-radius: var(--radius-box);
background-color: var(--color-base-200);
}
.table-card {
overflow-x: auto;
border: 1px solid var(--color-base-300);
border-radius: var(--radius-box);
background-color: var(--color-base-100);
}
.table-card:focus-visible {
outline: 2px solid var(--color-primary);
}
Terminal
npm run build
Look at the pages as in Figure 38.4: a details page on a phone, and the attendee list on a desktop, scrolled sideways if it is wider than its card.
Figure 38.4 — The details page at 390 pixels and the attendee list at 1280 pixels.
Record the design. In docs/design/erd.md, above “Out of scope for this release”:
docs/design/erd.md
Chapter 38 adds, for review:
- Profile: company, college, website, beside phone.
Event: asks_company, asks_college, asks_website.
- RegistrationQuestion: event, label, help text, kind,
required, choices, position, archived, added at. An
event has at most ten unarchived questions.
- Registration.answers: one JSON value, keyed by
q_<id>. Fixed facts are columns; each event's
own questions are answers (D38.4, the hybrid).
In docs/design/registration.md, the last line of “Not here” becomes “- The download of the attendee table: Chapter 41.”, followed by:
docs/design/registration.md
## Registration questions (Chapter 38)
- An event asks for profile facts (company, college,
website) and up to ten questions of eight kinds.
- Register sends a member with something to answer to
the details page (answers_needed); the answers and the
place are saved together, under the event's lock.
- A required question added later applies only to new
registrations; removing a question archives it and
keeps its answers; an answered choice cannot be
removed; an agreement keeps the time it was ticked
and cannot be unticked.
- Members change their answers until the start.
In docs/design/permissions.md, after “Proved by AttendeeMatrixTests”:
docs/design/permissions.md
Chapter 38: the attendee list also shows the profile
facts an event asks for and each member's answers, so
the same rows apply to them. A member changes only their
own answers (another member's place: 404, recorded).
Administrators read each event's questions in the admin
(registrations.view_registrationquestion, granted by
the migration registrations 0005_administrators).
and at the end of docs/adr/ADR-006-views.md:
docs/adr/ADR-006-views.md
## Update, Chapter 38
- attendees became AttendeesView (ListView with
LoginRequiredMixin), after its method table, because
this chapter changed it; it now answers 405 to methods
other than GET and HEAD.
- AnswersView (FormView) is new: a member changes their
answers until the event starts.
- RegistrationDetailsView builds its form at run time
from the event's questions.
Check and commit:
Terminal
uv run python check.py
Output
== python manage.py check
System check identified no issues (0 silenced).
== python manage.py makemigrations --check --dry-run
== python manage.py test --parallel
Found 423 test(s).
System check identified no issues (0 silenced).
Ran 423 tests in ...s
OK
== all checks passed
Terminal
git add .
git status --short
git commit -m "Ask each event's own questions"
Output
M accounts/forms.py
A accounts/migrations/0006_profile_facts.py
M accounts/models.py
M accounts/tests/test_accounts.py
M accounts/views.py
A audit/migrations/0003_change_answers.py
M audit/models.py
M config/helpers.py
M config/urls.py
M docs/adr/ADR-006-views.md
M docs/design/erd.md
M docs/design/permissions.md
M docs/design/registration.md
M events/admin.py
M events/forms.py
A events/migrations/0009_asks.py
M events/models.py
M events/templates/events/edit.html
M events/templates/events/event_fields.html
A events/templates/events/questions.html
M events/tests/test_events.py
M events/views.py
M registrations/forms.py
A registrations/migrations/0004_questions.py
A registrations/migrations/0005_administrators.py
M registrations/models.py
A registrations/templates/registrations/answers.html
M registrations/templates/registrations/attendees.html
R registrations/templates/registrations/phone.html ->
registrations/templates/registrations/details.html
M registrations/templates/registrations/panel.html
M registrations/templates/registrations/row.html
M registrations/templates/registrations/sharing.html
M registrations/tests/test_methods.py
A registrations/tests/test_questions.py
M registrations/tests/test_registrations.py
M registrations/urls.py
M registrations/views.py
M static/otahque/site.css
M static/otahque/source.css
A templates/django/forms/widgets/checkbox_option.html
A templates/django/forms/widgets/radio_option.html
[main 1a2b3c4] Ask each event's own questions
41 files changed, 1573 insertions(+), 110 deletions(-)
create mode 100644 accounts/migrations/0006_profile_facts.py
create mode 100644 audit/migrations/0003_change_answers.py
create mode 100644 events/migrations/0009_asks.py
create mode 100644 events/templates/events/questions.html
create mode 100644
registrations/migrations/0004_questions.py
create mode 100644
registrations/migrations/0005_administrators.py
create mode 100644
registrations/templates/registrations/answers.html
rename registrations/templates/registrations/{phone.html =>
details.html} (64%)
create mode 100644 registrations/tests/test_questions.py
create mode 100644
templates/django/forms/widgets/checkbox_option.html
create mode 100644
templates/django/forms/widgets/radio_option.html
If something goes wrong
Table 38.3 — Recovery for Chapter 38
Symptom
Likely cause
Recovery
"ManagementForm data is missing" on every save
{{ questions.management_form }} missing from the template
Add it inside the form
Saving the event works but questions never change
The formset is built but not saved in save_edit()
Call questions.save() after form.save()
Every existing edit test fails
as_sent() sends no management form
Step 6's helper change
Answers vanish after a question is reworded
Form fields named by label
Name them by question.key
A filter on answers__12 finds nothing
A key of digits is read as a list position
Keys are q_12
Register loops back to the details page
The profile change was not seen by register()
save_profile() sets self.member.profile
Radio buttons look like text boxes
The option templates are missing
Step 7's two templates
ProtectedError deleting a draft
Questions not deleted first
delete_draft() deletes them
autocomplete_fields error in check
The related admin has no search_fields
Add search_fields there
Anything else
A listing differs from yours
git diff shows your changes; git restore FILE returns a file to the last commit
Work through Table 38.4 from the folder that holds manage.py.
Table 38.4 — Verification checklist for Chapter 38
Check
Command or action
Expected result
Starting point
test --parallel
Found 399 test(s); OK
Attendee list pinned
test registrations.tests.test_methods
Found 6 test(s); OK
Migrations
makemigrations, then migrate
Four migrations made and applied
The Custom Way
uv run python practice_formset.py
Two copies valid; four refused; no management form refused
Builder
test registrations.tests.test_questions, Step 6
Found 8 test(s); OK
Registering
Same, Step 8
Found 12 test(s); OK
Attendee list and answers
Same, Step 9; then the tables
18 tests OK; the tables red, then declared
Copy and admin
Same, Steps 10 and 11
19, then 21 tests; OK
UI
Edit page, details page, attendee list at 390 and 1280 px
Question cards; radio buttons; the table scrolls inside its card; no sideways scroll of the page
All checks
uv run python check.py
== all checks passed; Ran 423 tests
Commit
git log --oneline -1
Ask each event's own questions
Not verified
macOS and Linux shells; browsers other than Edge
Chapter 64 adds CI on Linux for every push
The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 37 checkpoint with a reader’s data, against PostgreSQL 18; commands that write files ran once. The project folder is shortened to ... in printed output. The screenshots were taken in Microsoft Edge, with two sample events added for the screenshots only and deleted afterwards.
Que. 1 Why are company and college columns on Profile, but each event’s questions stored as answers in a JSON value?
Flip to check your answerFold answer back
Answer. Company and college have the same shape for every event, so they are columns the database can type and check, asked once and kept. Each event’s questions differ in number and kind, so they cannot be columns; a JSON value saved with the place holds whatever that event asked, in one write, without joins.
Que. 2 What does a formset need from the page besides the copies’ fields, and what happens without it?
Flip to check your answerFold answer back
Answer. The management form: hidden fields saying how many copies were sent and how many were existing rows. Without it the formset is invalid, with “ManagementForm data is missing or has been tampered with”, and nothing is saved.
Que. 3 A page sends a question row whose id belongs to another event. What happens?
Flip to check your answerFold answer back
Answer. The inline formset looks for that id only among this event’s questions, finds nothing, and saves nothing for that copy. The other event’s question is unchanged. It is safe, and quiet, so a test checks both events.
Que. 4 Why are the registration form’s fields named q_12, not “Python level”?
Flip to check your answerFold answer back
Answer. A label can be reworded; a key cannot. Named by key, answers stay with their question after a rewording, and the key is also the name in the JSON value, where a key of digits alone would be read as a list position.
Que. 5 Sam removes a question that thirty people answered. What happens to the answers?
Flip to check your answerFold answer back
Answer. Nothing: the question is archived, not deleted. It is no longer asked, and the attendee list still shows its column, marked as removed, with the thirty answers.
Mini-Challenge
A “Number” question takes whole numbers from zero. Write a test, in registrations/tests/test_number.py, that an answer of -1 on the details page is refused with Django’s “greater than or equal” message, and that no place is made.
Hint:RegistrationQuestion.objects.create() with kind=Q.Kind.NUMBER; the field is named by the question’s key.
Model answer:
registrations/tests/test_number.py
"""Mini-Challenge: a number answer below zero (38)."""
from django.test import TestCase
from registrations.models import Registration
from registrations.models import RegistrationQuestion as Q
from .test_registrations import soon, url, verified
class NumberAnswerTests(TestCase):
"""A number question takes whole numbers from zero."""
def test_a_negative_number_is_refused(self):
event = soon()
guests = Q.objects.create(event=event,
label='Guests you bring',
kind=Q.Kind.NUMBER)
sai = verified('sai@example.org')
self.client.force_login(sai)
response = self.client.post(
url('details', event.pk), {f'q_{guests.pk}': '-1'}
)
self.assertContains(response, 'greater than or equal')
self.assertFalse(Registration.objects.exists())
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s
OK
field_for() gives a number question min_value=0, so IntegerField refuses it before register() is called. The model answer was run and then removed; the chapter’s checkpoint does not include it.
What We Learned
Data with one shape belongs in columns; data whose shape changes per record can live in rows or a JSON value, each with costs.
A formset manages copies of one form under a prefix; an inline formset edits a parent’s rows.
The management form tells a formset how many copies to read; without it nothing is saved.
A tampered row id is ignored, not refused; test that nothing changed.
self.fields can be built in __init__(); name run-time fields by a stable key.
Save a parent and its formset in one transaction, under the same lock and version check.
Archive rows that other data depends on; PROTECT stops an accidental delete.
JSON keys of digits alone are read as list positions in lookups.
The admin’s list_filter, date_hierarchy, autocomplete_fields, and read-only inlines serve the administrator with little code.
Key terms
Use Table 38.5 to explain this chapter’s ideas in your own words.
Table 38.5 — Key terms from Chapter 38
Term
Meaning
Formset
Several copies of one form on a page, checked together.
Inline formset
A formset that edits the rows belonging to one parent object.
Management form
The hidden fields that tell a formset how many copies were sent.
Prefix
The start of each copy's field names, such as questions-0-.
Dynamic form
A form whose fields are added when it is built, from data.
JSONField
A model field holding a JSON value; jsonb on PostgreSQL.
Entity-attribute-value (EAV)
Storing each attribute of a record as a row of its own.
Archive
Mark a row as no longer in use instead of deleting it.
List filter
A choice in the admin's sidebar that narrows the list.
Date hierarchy
The admin's year, month, and day links above a list.
Autocomplete field
A search box in the admin instead of a dropdown of every row.
Readiness checkpoint: you are ready for Chapter 39 when uv run python check.py ends with “all checks passed” and 423 tests, Sam can add a question on his edit page and see the answers on the attendee list, Sai is asked it when she registers and can change it until the start, and git log --oneline -1 shows this chapter’s commit.
Git Commit
Your Chapter 38 work was committed once, in Step 12, as “Ask each event’s own questions”: the models and four migrations, the builder, the run-time form and its templates, the details, answers, and attendee pages, the admin, the tests and helpers, the styles, and the design notes. If you kept the Mini-Challenge, commit it on its own:
Terminal
git add registrations/tests/test_number.py
git commit -m "Refuse a negative number answer"
These five questions rehearse the chapter at interview level, from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead, to a common formset failure and to keeping data people gave you. They are extension questions, not a gate to the next chapter. Proof files are run with uv run python manage.py shell -v 0 -c "exec(open('NAME').read())" and deleted afterwards.
L1 (Junior): What is a formset?
What the interviewer is testing: Do you know what a formset adds to a form?
Flip to check your answerFold answer back
Perfect answer: A formset is a set of copies of one form, shown and checked together on one page. Each copy’s fields are named with a prefix and a number, such as questions-0-label, so copies never collide. A management form, four hidden fields, says how many copies were sent and how many of them were existing rows. The formset can offer empty copies for new rows, a tick box to remove a row, a limit on how many, and a clean() that checks across copies. An inline formset ties the copies to a parent object, such as an event’s questions.
Expecting extra empty copies to be validated; unchanged empty copies are skipped.
Follow-up the interviewer might ask:
Where does the prefix come from in an inline formset? (The related name of the foreign key, here questions.)
How would you add a copy without reloading? (Copy the empty form’s HTML and raise TOTAL_FORMS; Chapter 45 does it with HTMX.)
L2 (Mid-Level): Predict what a tampered question id from another event does
What the interviewer is testing: Do you know how an inline formset finds existing rows?
Flip to check your answerFold answer back
Perfect answer: Each existing copy sends its row’s id. The inline formset looks it up only in its queryset: this event’s unarchived questions. An id from Raj’s event is not there, so the copy has no object to change, and the formset saves nothing for it. The form is still valid, so there is no error message. Raj’s question is untouched, and so is Sam’s event’s set. The test must check the outcome, both events unchanged, not wait for a refusal that never comes.
Figure 38.5 — A question id from another event.
Behind the scenes:
An existing copy, in the formset
id from the page -> self.get_queryset() only
found: update that row
not found: no object; nothing saved for the copy
Code proof: the question tests, including the tampered row:
Output
Found 22 test(s).
Creating test database for alias 'default'...
...
Ran 22 tests in ...s
OK
Common mistakes:
Building the formset without instance=event, so its queryset is every question.
Testing for an error message that never appears.
Follow-up the interviewer might ask:
Would you make it an error? (Possibly, in clean(); Otahque keeps the quiet default and tests it.)
What else must the queryset leave out? (Archived questions, or they would come back.)
L3 (Senior): Defend columns for facts and JSON for answers
What the interviewer is testing: Can you choose a storage shape and name its costs?
Flip to check your answerFold answer back
Perfect answer: Company, college, and website are the same question for every event, so they are columns: typed, checked, asked once, and comparable across events in Chapter 41’s download. Each event’s own questions differ in number and kind, so they cannot be columns. A row per answer would give a foreign key and a unique rule, but every attendee list would need a join or a second query, and “several choices” would still need a format. One JSON value per place is saved with the place in the same write under the lock, read with the place, and holds lists, numbers, and true or false as they are. The cost is that the database does not check the answers, so the form and needs_answers() do, and keys must be q_<id> for lookups to read them as names. I would revisit if answers needed rules the database must enforce.
Code proof: the two field types, and a lookup by a question’s key:
Output
Profile company CharField
Registration answers JSONField
("registrations_registration"."answers" -> q_7) =
Jsonb('yes') ORDER BY
"registrations_registration"."registered_at" ASC
Common mistakes:
Putting fixed facts in JSON because it is easy, and losing types and checks.
Keys of digits, which lookups read as list positions.
Follow-up the interviewer might ask:
How would you find everyone who said yes to question 13? (Registration.objects.filter(answers__q_13='yes').)
Can PostgreSQL index that? (Yes, with an index on the expression or a GIN index; Chapter 55 measures first.)
L4 (Staff): “ManagementForm data is missing or has been tampered with”. Diagnose it
What the interviewer is testing: Can you read a formset error back to the page that caused it?
Flip to check your answerFold answer back
Perfect answer: The formset could not find TOTAL_FORMS or INITIAL_FORMS under its prefix in the posted data. The usual causes are a template that renders the copies but not {{ formset.management_form }}, a prefix that differs between the page and the view, or a test or script that posts the fields without the management form. Since Django 3.2 it is not a crash: the formset is invalid and the page shows the error, so nothing is saved, which is right. I would look at the posted data, the template, and the prefix, in that order. In Otahque, every test that posts the edit page goes through as_sent(), which was changed once, in Step 6, to send it.
Figure 38.7 — Diagnosing a missing management form.
Behind the scenes:
formset.is_valid()
management_form.is_valid()? no -> non-form error
otherwise: TOTAL_FORMS copies, each checked
Code proof: the builder posted without its management form:
Output
valid: False
ManagementForm data is missing or has been tampered with
Common mistakes:
Adding the management form outside the <form> element.
Changing the prefix in the view but not in JavaScript that adds rows.
Follow-up the interviewer might ask:
Why does Django not guess the number of copies? (Unticked boxes send nothing, so the posted data cannot say how many copies there were.)
Can a page raise the limit by sending a bigger MAX_NUM_FORMS? (No: the server uses the formset’s own max_num and ignores the posted value.)
L5 (Lead): Defend archiving a question instead of deleting it
What the interviewer is testing: Can you protect data people gave you from an easy delete?
Flip to check your answerFold answer back
Perfect answer: When Sam removes a question, thirty members may already have answered it. Their answers are what they told the organizer, and the attendee list, Chapter 41’s download, and any later dispute may need them. Deleting the question would orphan or destroy them. Archiving stops asking it, keeps it out of the ten, and keeps its column, marked as removed. The key to the event is PROTECT, so even an accidental delete of an event with questions fails loudly; delete_draft() deletes them on purpose, and only for a draft nobody registered for. Answers do leave in the end, by rule: Chapter 65 removes a closing member’s answers with the rest of their personal data.
Figure 38.8 — Why removing archives.
Table 38.7 — Deleting and archiving a question
Question
Delete
Archive
Asked again
No
No
Answers
Lost, or orphaned
Kept and shown
Counts towards ten
No
No
Undo
No
Yes, by clearing archived
Behind the scenes:
A ticked "Remove" box
formset.save() -> delete_existing(question)
Otahque: question.archived = True; save
Code proof: what removing does, and what deleting the event would meet:
Output
Archive a removed question; keep its answers.
on delete of the event: PROTECT
Common mistakes:
Using CASCADE because it is the default people reach for.
Archiving but still counting archived rows towards the limit.
Follow-up the interviewer might ask:
Should archived questions ever be purged? (By a retention rule, Chapter 65, not by a click.)
Could an organizer restore one? (Not on the site yet; the administrator can, and a future chapter may add it.)