Chapter 25 · Editing an event, and the validation lifecycle: Sam corrects his clinicCHAPTER 25
Complete six-part pre-release for review. Publishing is Chapter 26; until Chapter 27, signing in uses the admin's sign-in page. Two organizers editing at once is named here and handled in Chapter 33. No migration is added.
Working towards: First release (Chapter 34). One community runs free events. Members sign up, register, see, and cancel their registrations; organizers publish their own events; two people cannot both take the last place. Tests check each product rule. All milestones
CHAPTER TWENTY-FIVE
Editing an event, and the validation lifecycle: Sam corrects his clinic
Stage 4: Accounts and first release (Chapters 24 to 34)
Prerequisites: Chapters 15 to 24, including the Chapter 24 project, its 97 passing tests, Sam’s Online Django clinic saved as a draft, and the superuser account you created for Sam in Chapter 18
What you’ll build: An Edit event page that only an event’s current organizers can open; a form that shows the saved times in the event’s own zone, leaves any time Sam does not touch exactly as stored, and asks him to confirm, with both readings side by side, before a new time zone moves the event; a capacity that is refused beside its field and never set below the places already taken, in Otahque’s page and in the admin; proof that a crafted request changes nothing outside the form’s fields; and twenty-seven tests, which bring the project to 124.
Why This Matters
Sam’s Online Django clinic is saved, as a draft that only he and the administrator can see. Now the plans change, as plans do. The group in New York asks for a clearer title. The clinic may move from online to a room. Sam wants to raise the capacity, and later, perhaps, lower it again. Chapter 24 gave him a page to create an event, but nothing to change one: today his only way to correct the clinic is to create it again.
Editing sounds like creating with the boxes already filled in, and Django’s forms do most of it with one extra argument. But an edit page has dangers that a new event never meets, and each of them is quiet. Show the saved start in the wrong zone, and an organizer who changes only the title moves the event by five hours without noticing. Let anyone holding Django’s change permission open the page, and a staff account can rewrite every event, which Chapter 2’s PR-4 forbids: organizers manage only the events assigned to them. Lower the capacity to 1 when two members already hold places, and the event is over capacity before anyone registers again. Let the browser decide which fields it sends, and a crafted request publishes the event or changes who organizes it. None of these mistakes shows an error page. Each one just stores the wrong thing.
So this chapter does two jobs. It builds Sam’s Edit event page, and it opens up the part of Django that decides what an edit may store: the validation lifecycle, the fixed order in which a ModelForm checks each value, the form, the model, and the database’s rules, and decides where each message appears. Chapter 24 used that order. This chapter makes it visible, because every rule in the edit page has to be placed in it.
By the end of the chapter, you will be able to:
edit a saved row with a ModelForm and instance=, and say what is_valid() changes before save() is called;
name the stages of the validation lifecycle in order, and predict where each message appears;
check, for one event, whether a person may edit it, and choose between 403 and 404;
show stored times in the event’s own zone, keep untouched times exactly as stored, and confirm a change of zone with both readings shown together;
put a rule that spans two tables, capacity against the places already taken, in the model, so that Otahque’s pages and the admin both obey it;
prove with tests that a crafted request cannot change a field the form does not list, and name the edit conflict this chapter leaves for Chapter 33.
Publishing a draft is Chapter 26, members’ own sign-in pages Chapter 27, and showing each viewer times in their own zone Chapter 28. Telling members that an event has changed waits for email in Chapters 43 and 44.
Chapter 24’s EventForm created a new event. The same class can edit one, and that is all Chapter 24’s promise of “the same form” needs.
New Concept: a ModelForm with an instance
What problem exists? An edit page must start from the saved values, check what the person changes, and update that one row, never create a second one.
What did people do before? They loaded the row, copied each saved value into the page by hand, then copied each sent value back onto the row, as The Custom Way below does, and every copy was a chance to forget a check.
What is it? A ModelForm takes an optional instance= argument, a model object. Unbound, EventForm(instance=event) starts each field from the object’s values. Bound, EventForm(request.POST, instance=event) checks what was sent and copies the clean values onto that object, and its save() updates the object’s row instead of inserting a new one.
Why use it? One class, one allowlist, one set of rules for creating and editing, so a rule added for one page protects the other.
Now let’s use it. Step 3 opens the Edit event page with EventForm(instance=event), and Step 5 saves Sam’s changes.
Two details matter more on an edit than on a new event. First, a field missing from what the browser sends is not “left as it was”: a required field that is missing is an error, This field is required., exactly as on the New event page. The form never quietly keeps the stored value for a field that went missing, so a broken page cannot save half an event. Second, the allowlist still decides everything. Fields outside Meta.fields, such as status, are neither shown nor read, so an edit cannot publish a draft, and the organizer assignments, which are other rows entirely, cannot be touched through this form at all.
The validation lifecycle, in order
Chapter 24’s Under the Hood callout listed what is_valid() runs. On an edit, the order is worth learning by heart, because it decides which rule sees which value, and where its message appears. Figure 25.1 shows it.
Figure 25.1 — What is_valid() runs for an edit, in order; nothing reaches the database until save().
Table 25.1 lists the stages with what each one is for and where its message goes. Two rows are new in this chapter: Step 6 writes a clean_capacity() method, and a clean() method on the model.
Table 25.1 — The stages of is_valid() for a ModelForm
Stage
What belongs there
Where its message appears
Field
Required, length, number, choice
Beside the field
clean_<name>()
One more rule for one field
Beside that field
Form clean()
Rules comparing fields; ours
Beside the field named in add_error(), or at the top
Copy to instance
No rules; the instance changes
Nowhere
Model clean_fields()
Model field validators
Beside the field
Model clean()
Model rules that need queries
At the top, or beside a named field
validate_unique(), validate_constraints()
Chapter 21's rules
At the top; a unique rule on one field, beside it
Two consequences follow from that order. A rule that has already failed for a field stops later rules from checking it: when the form reports an error on Ends, the model skips Chapter 21’s “ends after it starts” constraint, so the message appears once. And the instance is changed before the model checks it, valid or not.
Under the Hood: what _post_clean() does
After the form’s clean(), a ModelForm runs a method called _post_clean(). It copies every value in cleaned_data that belongs to a model field onto the instance, so event.title now holds the typed title, then calls the instance’s full_clean() with every field that is not on the form excluded, and with the fields that already failed left out of the unique and constraint checks. Any message the model raises is added to the form’s errors. Django’s documentation warns that the instance is changed this way even when the form is invalid, and advises against reusing it. That is why Step 5’s view reads the event’s title before it binds the form: after an invalid post, event.title holds the text Sam typed, not the title that is saved.
save() is the only stage that writes. A ModelForm’s save(commit=False) returns the changed instance without writing it, so the view can set something the form does not own, then call the instance’s save() itself. Otahque has no such value on the edit page, so it does not need commit=False: Chapter 24 already records the organizer after save(), in the same transaction. Step 2 shows both in a practice file.
Who may edit an event
Chapter 23 and Chapter 24 used Django’s model permissions, such as events.change_event. A model permission says what a person may do to every event, and Django checks only that. It knows nothing about who organizes which event, and its documentation leaves a check for one object to the project. Chapter 2’s PR-4 needs exactly that: organizers manage only the events assigned to them.
So the edit page asks two questions, and both must be yes: does the person hold events.change_event, and does Chapter 20’s OrganizerAssignment record them as a current organizer of this event? An administrator who holds the permission but organizes nothing is refused here, and uses the admin site, which Chapter 23 made the administrator’s tool. Figure 25.2 shows the answers.
Figure 25.2 — Who may open the Edit event page: the permission and a current assignment, both.
The two refusals differ on purpose. A person who may see the event, because it is published or because they hold view_event, gets 403 Forbidden: the page exists, and they may not use it. A person who may not even see the event, such as Sai looking at Sam’s draft, gets 404 Not Found, as on the draft’s own page in Chapter 24: answering 403 would tell her that a draft with that number exists. So the view checks visibility first and the edit right second.
A saved time, shown and kept
The event’s starts_at is stored as one instant in UTC, and its zone as a name. The box on the page holds clock text, such as 2026-12-03T19:00. Editing turns the stored instant into text and, when Sam presses Save changes, turns the text back into an instant. Figure 25.3 follows that round trip.
Figure 25.3 — A saved time’s round trip: shown in the event’s zone, kept when untouched, read again when changed, and confirmed when the zone changes.
Three rules come from it, each decided for Otahque in this chapter’s plan:
Shown in the event’s zone. Django writes a stored time into a box in the current zone, UTC, so Sam would see 00:00 on 4 December for his 19:00 clinic. Pressing Save changes without touching it would then read 00:00 as New York time and store 05:00 UTC: the event moves five hours, and the form calls it valid. The edit form therefore converts each stored time to the event’s zone before showing it, and adds a line under the box with both clocks together: the event’s time and the same instant in UTC.
Kept when untouched. If the zone is unchanged and the text in a box is exactly what the page showed, the stored instant is kept and the text is not read again. That keeps any seconds a stored time has, which the box cannot show, and it saves an event whose start falls in a repeated hour, such as 01:30 on 1 November in New York. Chapter 24’s form refuses that text, because it could mean either 01:30, but a time stored by the admin or an import can sit there, and without this rule Sam could not even correct the title.
Confirmed when the zone changes. Changing Time zone alone re-reads the clock text in the new zone, as creating an event does, so the event happens at a different moment. Because that is easy to do by accident, the form refuses the first save, shows the saved reading and the new one together, and adds a tick box, Yes, move the event to this zone. Ticking it and saving again stores the new instant.
Other event services make the same choice in different ways. Luma shows an event’s own time with the viewer’s local time beside it in parentheses, and users of content tools complain about whichever reading they did not expect. No rule is right everywhere. What matters is one clear rule, stated on the page, with both clocks shown together.
Capacity and the places already taken
Chapter 21 made the database refuse a capacity below 1, and Chapter 24’s form reported that refusal at the top of the page, because a model constraint’s message belongs to the whole form. Chapter 2’s PR-3 adds a second rule for an edit: a capacity reduction that would leave fewer places than members already hold is refused. A database CHECK cannot state that, because it compares a row of one table with a count from another. The model’s clean() method can, and because the admin’s forms call the model’s validation too, a rule there protects both Otahque’s page and the admin. Figure 25.4 shows the three layers that now guard capacity.
Figure 25.4 — Three layers guard an event’s capacity, from the friendliest message to the last line.
The count and the save are two steps. If a member registers between them, the event can still end up one place short. Closing that gap needs a database lock, which Chapter 33 adds for the last available place; this chapter states the rule and tests it.
What a crafted request can and cannot change
A browser sends whatever the page holds, and a script sends whatever its author wants. An edit form must assume both. Figure 25.5 shows what a crafted POST to the edit page can reach.
Figure 25.5 — On an edit, the allowlist decides what a request can write; everything else is ignored.
The rule is the same as for a new event, and Step 7 proves it with tests rather than trust. The tests matter because the edit page has more to lose: a crafted status would publish a draft, and a crafted id that the form obeyed could overwrite another event.
Two organizers, one event
An event can have several current organizers. Suppose Sam and a co-organizer both open the edit page in the morning. Sam changes the location and saves. Later, the co-organizer, whose page still holds the old location, changes the capacity and saves. The second save writes every field on its form, so the old location goes back: Sam’s change is lost, and nobody is told. This is a lost update, and the usual cure is a version check: the page carries the version it was opened at, and a save from an older version is refused with a message to reload. Step 8 shows the lost update in a practice file, and why the tempting shortcut of saving only the changed fields does not prevent it. Building the version check needs a new field and a migration, so it waits for Chapter 33, beside the lock on the last available place, and Chapter 47 gives Otahque’s future programming interface the same protection through HTTP. Until then, the last save wins, and the design note says so.
Try it yourself
Que. 1 Sam opens the clinic’s edit page, changes nothing, and presses Save changes. The page shows the start as 2026-12-03T19:00, and the stored start is midnight UTC on 4 December. What is stored after the save, and which rule decides it?
Flip to check your answerFold answer back
Answer. Midnight UTC on 4 December, unchanged. The zone is unchanged and the text is exactly what the page showed, so the form keeps the stored instant instead of reading the text again.
Que. 2 Sai is signed in and opens /events/6/edit/, the edit page for Sam’s draft. Which status does she get, and why not the other refusal?
Flip to check your answerFold answer back
Answer. 404 Not Found. Sai may not see the draft at all, so the view answers as if it did not exist. A 403 would tell her that event 6 is a draft she is not allowed to edit.
Prefer one form for creating and editing, or two?
Use one ModelForm when the fields and rules are the same, as for Sam’s events: one allowlist and one set of messages, with a few lines that run only when the form has a saved instance. Split into a second class only when the pages genuinely differ, such as a field that can be set once and never changed; then share the rules through a parent class, not by copying them.
Start from Chapter 24, in the folder containing manage.py, with your own .env, the locked environment, 97 passing tests, every migration applied, the Node.js packages from Chapter 14 installed, Sam’s superuser password from Chapter 18, and the Online Django clinic you saved as a draft in Chapter 24, event 6. Step 2 watches the validation lifecycle in a practice file. Step 3 adds the Edit event page and its access rule: two model methods in events/models.py, a view in events/views.py, an address in events/urls.py, the template events/templates/events/edit.html, and a link on the event page. Step 4 teaches events/forms.py to show and keep saved times. Step 5 saves edits. Step 6 guards capacity in the model and the form. Step 7 proves that crafted fields change nothing. Step 8 styles the tick box and long help lines, through one new widget template, Chapter 24’s field template, and static/otahque/source.css. Step 9 proves the CSRF protection on the new page, updates the design note, and commits. Every test goes in events/tests.py. At the end, 124 tests pass, Sam can edit his clinic without moving it by accident, and there is no new migration.
The Custom Way
Without a ModelForm, an edit page copies values by hand, in both directions. This illustration shows the two ways that goes: copying everything that was sent, and copying carefully. Run it with any Python, and do not add it to the project:
illustration_only/by_hand.py (not part of the project)
STORED = {'title': 'Online Django clinic',
'status': 'draft', 'capacity': 50}
SENT = {'title': 'Clinic', 'capacity': '1',
'status': 'published'}
def update_everything(row, sent):
for name, value in sent.items():
row[name] = value
return row
def update_carefully(row, sent, places_taken):
errors = {}
row = dict(row, title=sent.get('title', '').strip())
if not row['title']:
errors['title'] = 'This field is required.'
try:
row['capacity'] = int(sent.get('capacity', ''))
except ValueError:
errors['capacity'] = 'Enter a whole number.'
else:
if row['capacity'] < places_taken:
errors['capacity'] = 'Below the places taken.'
return errors or row
print(update_everything(dict(STORED), SENT))
print(update_carefully(STORED, SENT, places_taken=2))
print(update_carefully(STORED, SENT | {'capacity': '40'},
places_taken=2))
The first version does what the request asks: the title changes, the capacity becomes the text '1' instead of a number, and status becomes published, because the request said so. The careful version names the fields it allows, converts the capacity, and refuses a value below the places taken. It is already twenty lines for two fields, and it still has no labels, no redisplay, no times, no zones, and no check of who is asking. Every rule is a copy of one the model already holds. The Django Way below keeps the careful version’s ideas and lets the form and the model do the copying.
The Django Way
Nine steps follow. Step 1 checks the start, Step 2 watches the lifecycle, Step 3 builds the page and its access rule, Steps 4 and 5 show, keep, and save times and edits, Step 6 guards capacity, Step 7 proves the allowlist, Step 8 finishes the page’s look, and Step 9 proves the CSRF protection, records the design, and commits. Each step writes its tests first.
Step 1: Check the starting point
Run every test, beside manage.py, in PowerShell, Git Bash, a macOS shell, or Linux/WSL Bash:
Terminal
uv run python manage.py test
Expected result, shortened with ...:
Output
Found 97 test(s).
Creating test database for alias 'default'...
...
Ran 97 tests in ...
OK
Destroying test database for alias 'default'...
Then confirm that nothing is waiting to be committed and that the last commit is Chapter 24’s:
Terminal
git status --short
git log --oneline -1
Output
... Add the new event form
git status --short prints nothing when every change is committed. Your commit’s code, the seven characters before the message, differs from the one shown.
Step 2: Watch the lifecycle in a practice file
Before changing anything, watch Chapter 24’s EventForm edit Sam’s clinic, and record each stage it runs. Create practice/lifecycle.py, in the practice folder beside your project:
traced() wraps one of the model’s methods so that it records its name before doing its normal work, and the loop puts a wrapper around four of them. TracedForm is EventForm with two methods that record themselves too: clean_title(), a rule for one field, and clean(), which calls Chapter 24’s. The sent values change the title and set the capacity to 0. The wrappers last only while this file runs; your project is not changed. Run it from the folder that holds manage.py:
Terminal
uv run python ../practice/lifecycle.py
Output
False
form clean_title()
form clean()
model clean_fields()
model clean()
model validate_unique()
model validate_constraints()
__all__ Capacity must be more than 0.
in memory: Django clinic 0
stored: Online Django clinic 50
commit=False: Django clinic 40
stored: Online Django clinic 50
Read it from the top. The form is invalid. The calls ran in the order of Figure 25.1: the field rule, the form’s clean(), then the model’s four stages. The message comes from Chapter 21’s constraint, under __all__, the key for messages that belong to the whole form, which is why Chapter 24’s page showed it at the top. Then the warning from the lifecycle: the instance in memory holds the typed title and capacity, although nothing was saved, as refresh_from_db() shows. The last lines bind a valid form and call save(commit=False): the returned event holds the new values, and the stored row is still unchanged, because nothing called the event’s save().
Step 3: Who may edit
The access tests come first: a visitor is sent to sign in, Sai may see the published meetup but not edit it, Sam’s draft is “not found” for her, Sam gets the form, an organizer whose assignment is revoked is refused, an administrator who organizes nothing is refused, and only Sam sees the Edit event link. Add at the end of events/tests.py:
events/tests.py (add at the end)
def editor(email='sam@example.org'):
"""Make a member who may create and change events."""
return member(email, 'add_event', 'change_event')
def save_clinic(organizer):
"""Sam's clinic, saved as a draft through EventForm."""
clinic = EventForm(NEW_EVENT).save()
clinic.add_organizer(organizer)
return clinic
def edit_url(event):
"""Return the edit page's address for event."""
return reverse('events:edit', args=[event.pk])
class EditAccessTests(TestCase):
"""Who may open an event's edit page."""
@classmethod
def setUpTestData(cls):
cls.sam = editor()
cls.sai = member('sai@example.org')
cls.admin = member('admin@example.org',
'view_event', 'change_event')
cls.clinic = save_clinic(cls.sam)
cls.meetup = save_event()
def test_visitor_is_sent_to_sign_in(self):
url = edit_url(self.clinic)
response = self.client.get(url)
sign_in = reverse('admin:login')
self.assertRedirects(
response, f'{sign_in}?next={url}',
fetch_redirect_response=False,
)
def test_member_may_see_but_not_edit(self):
self.client.force_login(self.sai)
response = self.client.get(edit_url(self.meetup))
self.assertEqual(response.status_code, 403)
def test_hidden_draft_is_not_found(self):
self.client.force_login(self.sai)
response = self.client.get(edit_url(self.clinic))
self.assertEqual(response.status_code, 404)
def test_organizer_gets_the_form(self):
self.client.force_login(self.sam)
response = self.client.get(edit_url(self.clinic))
self.assertTemplateUsed(response, 'events/edit.html')
self.assertContains(
response, 'value="Online Django clinic"'
)
def test_revoked_organizer_is_refused(self):
place = self.meetup.add_organizer(self.sam)
self.client.force_login(self.sam)
url = edit_url(self.meetup)
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
place.revoked_at = timezone.now()
place.save()
response = self.client.get(url)
self.assertEqual(response.status_code, 403)
def test_administrator_who_is_no_organizer(self):
self.client.force_login(self.admin)
response = self.client.get(edit_url(self.clinic))
self.assertEqual(response.status_code, 403)
def test_edit_link_only_for_who_may_edit(self):
page = reverse('events:detail',
args=[self.clinic.pk])
link = f'href="{edit_url(self.clinic)}"'
for person, count in ((self.sam, 1),
(self.admin, 0)):
with self.subTest(person=person.email):
self.client.force_login(person)
response = self.client.get(page)
self.assertContains(response, link,
count=count)
editor() uses Chapter 24’s member() helper to make a member who holds both permissions. save_clinic() saves Sam’s clinic through the form, as his browser would, and records the organizer. Run the new tests:
Terminal
uv run python manage.py test events.tests.EditAccessTests
Expected result, shortened with ...:
Output
Found 7 test(s).
...
EEEEEEE
...
ERROR: test_administrator_who_is_no_organizer (...)
...
django.urls.exceptions.NoReverseMatch: Reverse for 'edit'...
...
FAILED (errors=7)
Every test stops at reverse('events:edit', ...), because the address does not exist yet. Start in events/models.py. Replace the method is_visible_to() of Event with these three methods:
events/models.py (is_visible_to, replaced)
def has_organizer(self, user):
"""Return True if user is a current organizer."""
if not user.is_authenticated:
return False
return self.organizer_assignments.filter(
member=user, revoked_at__isnull=True
).exists()
def is_visible_to(self, user):
"""Whether user may see this event.
Published: everyone. Otherwise: organizers and
holders of the view_event permission.
"""
if self.status == self.Status.PUBLISHED:
return True
if user.has_perm('events.view_event'):
return True
return self.has_organizer(user)
def can_be_edited_by(self, user):
"""Holders of change_event who organize it."""
return (user.has_perm('events.change_event')
and self.has_organizer(user))
has_organizer() is the question Chapter 24 asked inside is_visible_to(), moved into its own method so that both rules share it, as Chapter 22’s “fat models, thin views” asks. can_be_edited_by() answers P1 of this chapter’s plan: the permission and a current assignment, both. A visitor holds no permissions, so has_perm() returns false for them without asking the database, and and then skips the second question.
In events/views.py, add one import before from django.db import transaction:
events/views.py (before from django.db import transaction)
from django.core.exceptions import PermissionDenied
Replace the function event_detail() so that it tells the page whether to show the link:
events/views.py (event_detail, replaced)
def event_detail(request, event_id):
"""Show an event its viewer may see, or 404."""
event = get_object_or_404(
Event.objects.with_places(), pk=event_id
)
if not event.is_visible_to(request.user):
raise Http404('No event matches the given query.')
return render(request, 'events/detail.html', {
'event': event,
'now': timezone.now(),
'can_edit': event.can_be_edited_by(request.user),
})
And add the new view at the end of the file:
events/views.py (add at the end)
@login_required
def event_edit(request, event_id):
"""Edit the event, for those who may change it."""
event = get_object_or_404(Event, pk=event_id)
if not event.is_visible_to(request.user):
raise Http404('No event matches the given query.')
if not event.can_be_edited_by(request.user):
raise PermissionDenied
form = EventForm(instance=event)
return render(request, 'events/edit.html', {
'form': form,
'event': event,
})
login_required sends a visitor to sign in. The view then asks the two questions in order: may this person see the event at all, and if so, may they edit it. Raising PermissionDenied makes Django answer 403. For now the view only shows the form; Step 5 handles what it sends. In events/urls.py, add the address after the events/<int:event_id>/ pattern:
events/urls.py (after the events/<int:event_id>/ pattern)
Create the template events/templates/events/edit.html:
events/templates/events/edit.html
{% extends "base.html" %}
{% block title %}Edit event | Otahque{% endblock %}
{% block content %}
<h1>Edit {{ event.title }}</h1>
<form method="post" class="card space-y-4 border
border-base-300 bg-base-100 p-6">
{% csrf_token %}
{{ form }}
<button type="submit" class="btn btn-primary">
Save changes</button>
</form>
<p>
<a href="{% url 'events:detail' event.pk %}">
Back to the event</a>
</p>
{% endblock %}
It is Chapter 24’s form.html with a different heading and button, and without the zone script, because a saved event already has its zone. Finally, in events/templates/events/detail.html, add the link after <p>{{ event.location }}</p>:
events/templates/events/detail.html (after the location paragraph)
uv run python manage.py test events.tests.EditAccessTests
Output
Found 7 test(s).
Creating test database for alias 'default'...
...
Ran 7 tests in ...
OK
Destroying test database for alias 'default'...
Common Error: asking about editing before seeing
If the view raises PermissionDenied before it checks is_visible_to(), Sai gets 403 for Sam’s draft, and test_hidden_draft_is_not_found fails with AssertionError: 403 != 404. The page has told her that event 6 exists and is not published. Check visibility first, so a hidden event is “not found” for everyone who may not see it.
Start the server, if it is not running:
Terminal
uv run python manage.py runserver
Sign in as Sam at http://127.0.0.1:8000/admin/login/?next=/events/6/, the clinic’s page. Under the location there is now an Edit event link; follow it. The page is headed “Edit Online Django clinic”, and every box holds the clinic’s values, except one thing. Look at Starts: it shows 4 December, at midnight. That is midnight UTC, not 19:00 in New York. Do not press Save changes; Step 4 explains why it matters even though this view saves nothing yet.
Step 4: Show saved times in the event’s zone, and keep them
The tests say what the form must do with a saved event: show 19:00 on 3 December with a line of both readings; keep a time the page showed and Sam left alone, seconds and all; save an event whose start falls in New York’s repeated hour; move only the end when only the end changes; refuse a new zone until the tick box is ticked, showing both readings; read the typed time in the new zone once it is ticked; and show no tick box when the zone stays. Add at the end of events/tests.py:
events/tests.py (add at the end)
def as_sent(event, **changes):
"""Return what the edit page sends, before any change."""
form = EventForm(instance=event)
data = {}
for name in form.fields:
value = form[name].value()
if isinstance(value, datetime):
value = f'{value:%Y-%m-%dT%H:%M}'
data[name] = value
return data | changes
def edit_form(event, **changes):
"""Return the edit form for event, sent with changes."""
data = as_sent(event, **changes)
return EventForm(data, instance=event)
SAVED_NOW = ('Saved now: 3 December 2026, 19:00 '
'America/New_York (4 December, 00:00 UTC). ')
class EditFormTests(TestCase):
"""Editing times and the event's time zone."""
@classmethod
def setUpTestData(cls):
cls.clinic = save_clinic(editor())
def test_saved_times_are_shown_in_the_event_zone(self):
form = EventForm(instance=self.clinic)
self.assertIn('value="2026-12-03T19:00"',
str(form['starts_at']))
self.assertEqual(
form.fields['starts_at'].help_text,
'Saved: 3 December 2026, 19:00 America/New_York '
'(4 December, 00:00 UTC)',
)
def test_unchanged_times_keep_their_stored_value(self):
stored = datetime(2026, 12, 4, 0, 0, 30, tzinfo=UTC)
Event.objects.filter(pk=self.clinic.pk).update(
starts_at=stored
)
self.clinic.refresh_from_db()
form = edit_form(self.clinic, title='Django clinic')
self.assertTrue(form.is_valid(), form.errors)
self.assertEqual(form.save().starts_at, stored)
def test_a_repeated_hour_saves_unchanged(self):
event = save_event(
timezone='America/New_York',
starts_at=datetime(2026, 11, 1, 6, 30,
tzinfo=UTC),
ends_at=datetime(2026, 11, 1, 8, 0, tzinfo=UTC),
)
stored = event.starts_at
form = edit_form(event, location='Room 2')
self.assertTrue(form.is_valid(), form.errors)
self.assertEqual(form.save().starts_at, stored)
def test_changing_the_end_moves_only_the_end(self):
form = edit_form(self.clinic,
ends_at='2026-12-03T21:00')
self.assertTrue(form.is_valid(), form.errors)
event = form.save()
self.assertEqual(
event.starts_at,
datetime(2026, 12, 4, 0, 0, tzinfo=UTC),
)
self.assertEqual(
event.ends_at,
datetime(2026, 12, 4, 2, 0, tzinfo=UTC),
)
def test_a_new_zone_needs_the_tick_box(self):
form = edit_form(self.clinic,
timezone='Europe/London')
self.assertIn('confirm_zone', form.fields)
self.assertFormError(
form, 'timezone',
SAVED_NOW + 'With this zone: 3 December 2026, '
'19:00 Europe/London (3 December, 19:00 UTC). '
'Tick the box to save the new zone.',
)
def test_a_ticked_new_zone_reads_the_typed_time(self):
form = edit_form(self.clinic,
timezone='Europe/London',
confirm_zone='on')
self.assertTrue(form.is_valid(), form.errors)
self.assertEqual(
form.save().starts_at,
datetime(2026, 12, 3, 19, 0, tzinfo=UTC),
)
def test_no_tick_box_when_the_zone_is_kept(self):
for form in (EventForm(instance=self.clinic),
edit_form(self.clinic),
new_event_form()):
self.assertNotIn('confirm_zone', form.fields)
as_sent() builds what the edit page sends back before any change: for each field, the value the page shows, with dates and times written the way the browser’s box sends them. edit_form() binds the form to that, with changes. Run the tests:
Terminal
uv run python manage.py test events.tests.EditFormTests
Six fail, and the second shows the danger plainly: a form sent back unchanged stores a start five hours later than the one it was given, because the page showed midnight UTC and the form read it as midnight in New York. Only the last test passes, because there is no tick box yet at all.
Open events/forms.py. Replace the function local_input() with this constant and the function, now using it:
events/forms.py (local_input, replaced)
BOX_FORMAT = '%Y-%m-%dT%H:%M'
def local_input():
"""Make a date-and-time box that the browser fills in."""
return forms.DateTimeInput(
attrs={'type': 'datetime-local'},
format=BOX_FORMAT,
)
BOX_FORMAT is the text form of a date and time that a datetime-local box reads and sends; the form uses it both to fill the box and to compare what comes back. Add this function after in_zone(), with two blank lines before and after it:
events/forms.py (after in_zone)
def reading(moment, zone_name):
"""Say when moment is, in zone_name and in UTC."""
local = moment.astimezone(ZoneInfo(zone_name))
utc = moment.astimezone(UTC)
return (f'{local.day} {local:%B %Y, %H:%M} {zone_name}'
f' ({utc.day} {utc:%B, %H:%M} UTC)')
reading() says when an instant is, twice: as clock time in the named zone, and in UTC, so the page can show both together. Inside EventForm, add these methods after the Meta class, with one blank line before them:
events/forms.py (EventForm, after Meta)
def __init__(self, *args, **kwargs):
"""Show saved times; ask before a zone change."""
super().__init__(*args, **kwargs)
self.saved_zone = self.instance.timezone
self.shown = {}
if self.instance.pk:
self.show_saved_times()
if self.zone_changed():
self.fields['confirm_zone'] = forms.BooleanField(
required=False,
label='Yes, move the event to this zone',
)
self.order_fields(
['title', 'timezone', 'confirm_zone']
)
def show_saved_times(self):
"""Show stored times as typed in the event's zone."""
zone = ZoneInfo(self.saved_zone)
for name in ('starts_at', 'ends_at'):
moment = getattr(self.instance, name)
local = moment.astimezone(zone)
local = local.replace(tzinfo=None)
self.initial[name] = local
self.shown[name] = local.strftime(BOX_FORMAT)
self.fields[name].help_text = (
'Saved: ' + reading(moment, self.saved_zone)
)
def zone_changed(self):
"""Return whether an edit changes the saved zone."""
if not self.is_bound or self.instance.pk is None:
return False
return self.data.get('timezone') != self.saved_zone
__init__() runs whenever a form is created. After the ModelForm has filled in the instance’s values, it remembers the saved zone. For a saved event, show_saved_times() converts each stored time to the event’s zone, puts that clock time in the form’s initial values, which the box shows, remembers the exact text shown in self.shown, and writes the line of both readings as the field’s help text, so Chapter 24’s field template displays it and links it with aria-describedby. When an edit sends a zone that differs from the saved one, __init__() adds a tick box, confirm_zone, and order_fields() places it just after Time zone. The tick box is not a model field, so the form checks it but never saves it.
Last, replace the whole clean() method, at the end of the file, with these three methods:
events/forms.py (clean, replaced)
def clean(self):
"""Read times in the zone; ask before a new zone."""
data = super().clean()
zone = data.get('timezone')
for name in ('starts_at', 'ends_at'):
if zone and data.get(name):
try:
data[name] = self.read_time(
name, data[name], zone
)
except ValidationError as error:
self.add_error(name, error)
starts = data.get('starts_at')
ends = data.get('ends_at')
if starts and ends and ends <= starts:
self.add_error(
'ends_at',
'An event must end after it starts.',
)
if self.zone_changed() and not data.get(
'confirm_zone'):
self.ask_about_zone(data)
return data
def read_time(self, name, value, zone):
"""Keep a time left alone; read others in zone."""
typed = timezone.make_naive(value)
unchanged = (zone == self.saved_zone and
typed.strftime(BOX_FORMAT)
== self.shown[name])
if unchanged:
return getattr(self.instance, name)
return in_zone(value, zone)
def ask_about_zone(self, data):
"""Show both readings before a new zone is saved."""
zone = data.get('timezone')
starts = data.get('starts_at')
if not zone:
return
message = 'Tick the box to save the new zone.'
params = {}
if starts:
message = ('Saved now: %(saved)s. With this '
'zone: %(new)s. ' + message)
params = {
'saved': reading(self.instance.starts_at,
self.saved_zone),
'new': reading(starts, zone),
}
self.add_error('timezone', ValidationError(
message, code='zone_changed', params=params,
))
clean() is Chapter 24’s, with two changes: each time goes through read_time() instead of straight to in_zone(), and an edit that changes the zone without the tick box goes to ask_about_zone(). read_time() keeps the stored instant when the zone is the saved one and the text is exactly the text the page showed; otherwise it reads the text in the zone, as before. ask_about_zone() adds one message to Time zone, with the saved reading and the new one side by side. Run the tests again:
Terminal
uv run python manage.py test events.tests.EditFormTests
Output
Found 7 test(s).
Creating test database for alias 'default'...
...
Ran 7 tests in ...
OK
Destroying test database for alias 'default'...
And run every events test, to see that the New event page still behaves:
Terminal
uv run python manage.py test events
Expected result, shortened with ...:
Output
Found 78 test(s).
Creating test database for alias 'default'...
...
Ran 78 tests in ...
OK
Destroying test database for alias 'default'...
Under the Hood: why the form compares text, not times
Django can tell you which fields changed, through form.changed_data, but it compares the text sent with the initial value read in the current zone, UTC, so it reports both times as changed even when Sam touched neither. The form knows better: it remembers the exact text it put in each box, and compares the text that comes back. Text is also what Sam controls. A repeated hour, such as 01:30 on 1 November in New York, shows as the same 01:30 for both readings, so reading it again would have to guess. Keeping the stored instant needs no guess.
Reload the edit page in the browser. Starts now shows 19:00 on 3 December, and under it, in grey: “Saved: 3 December 2026, 19:00 America/New_York (4 December, 00:00 UTC)”. Ends shows the same for 20:30.
Step 5: Save, then redirect
The view still ignores what is sent. The tests say what it should do: a valid edit redirects to the event page with “Changes saved.”; an invalid edit returns the page with every typed value, saves nothing, and keeps the saved title in the heading; the page shows both readings of the times; and when members hold places, the page says how many, without counting cancelled places. Add at the end of events/tests.py:
uv run python manage.py test events.tests.EditPageTests
Expected result, shortened with ...:
Output
Found 4 test(s).
...
FAIL: test_a_saved_edit_redirects_with_a_message (...)
...
AssertionError: [] is not true : Response didn't redirect...
...
FAIL: test_invalid_edit_keeps_values_saves_nothing (...)
...
FAIL: test_places_taken_are_counted (...)
...
FAILED (failures=3)
Three fail. The view never saves or redirects, it answers a POST with the saved values, unchecked, instead of what Sam typed and its messages, and there is no count of places. In events/models.py, add this method to Event, after can_be_edited_by():
events/models.py (Event, after can_be_edited_by)
def places_taken(self):
"""How many members hold a place now."""
return self.registrations.active().count()
registrations is the reverse name Chapter 20 gave Registration.event, and active() is Chapter 22’s QuerySet method, which every related manager of a registration also has. In events/views.py, replace event_edit() with:
events/views.py (event_edit, replaced)
@login_required
def event_edit(request, event_id):
"""Edit the event, for those who may change it."""
event = get_object_or_404(Event, pk=event_id)
if not event.is_visible_to(request.user):
raise Http404('No event matches the given query.')
if not event.can_be_edited_by(request.user):
raise PermissionDenied
title = event.title
if request.method == 'POST':
form = EventForm(request.POST, instance=event)
if form.is_valid():
form.save()
messages.success(request, 'Changes saved.')
return redirect('events:detail', event.pk)
else:
form = EventForm(instance=event)
return render(request, 'events/edit.html', {
'form': form,
'title': title,
'event_id': event.pk,
'taken': event.places_taken(),
})
It follows Chapter 24’s event_create(): a POST binds the form, a valid form saves and redirects with a message, and an invalid one falls through to the same page with the bound form. Three things are new. instance=event makes save() update event 6 instead of inserting a new one. title = event.title is read before the form is bound, because is_valid() changes the instance, even when it fails. And taken counts the places for the page. Replace events/templates/events/edit.html with:
events/templates/events/edit.html (replaced)
{% extends "base.html" %}
{% block title %}Edit {{ title }} | Otahque{% endblock %}
{% block content %}
<h1>Edit {{ title }}</h1>
{% if taken %}
<p class="rounded-box border border-base-content
px-3 py-1 text-sm">
Places taken: {{ taken }}. Otahque does not tell
members about changes yet.</p>
{% endif %}
<form method="post" class="card space-y-4 border
border-base-300 bg-base-100 p-6">
{% csrf_token %}
{{ form }}
<button type="submit" class="btn btn-primary">
Save changes</button>
</form>
<p>
<a href="{% url 'events:detail' event_id %}">
Back to the event</a>
</p>
{% endblock %}
The template now reads title and event_id instead of the event, and shows the count of places, when there are any, with the same border as the draft note on the event page. The sentence says what Otahque does today; it is not a promise, and Chapters 43 and 44 revisit it when email exists. Run the tests again:
Terminal
uv run python manage.py test events.tests.EditPageTests
Output
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...
OK
Destroying test database for alias 'default'...
Common Error: the heading shows what Sam typed
Passing the event’s title at render time, 'title': event.title, looks harmless, but by then is_valid() has copied the typed title onto the event. After an invalid post, the heading would read “Edit Django clinic” for an event still called “Online Django clinic”, and test_invalid_edit_keeps_values_saves_nothing fails with AssertionError: False is not true : Couldn't find '<h1>Edit Online Django clinic</h1>' in the following response. Read anything you need from the saved event before binding the form.
Common Error: forgetting instance= on the POST
EventForm(request.POST) without instance=event is a form for a new event. A valid edit then inserts a second event, a copy with the changes, while the view redirects to the original, which stays as it was. test_a_saved_edit_redirects_with_a_message fails with AssertionError: False is not true : Couldn't find '<h1>Django clinic</h1>' in the following response. Pass the instance to both forms, the empty one and the bound one.
In the browser, reload the edit page, change Ends to 21:00, and press Save changes. The event page opens with “Changes saved.” and “Until Thursday 3 December 2026, 21:00 EST”. Open the edit page again and choose Europe/London in Time zone, changing nothing else, then press Save changes. The page returns with a message under Time zone: “Saved now: 3 December 2026, 19:00 America/New_York (4 December, 00:00 UTC). With this zone: 3 December 2026, 19:00 Europe/London (3 December, 19:00 UTC). Tick the box to save the new zone.” A new field, Yes, move the event to this zone, appears below it, drawn for now as a wide empty box; Step 8 makes it a proper tick box. Do not tick it: choose America/New_York again and leave the page.
Step 6: Guard capacity in the form and the model
Capacity now gets two rules on Sam’s pages: 0 is refused beside Capacity, and an edit may not set it below the places already taken, in Otahque’s page and in the admin. Chapter 24 had a test that expected the opposite of the first rule, so it changes now. In events/tests.py, inside EventFormTests, replace the method test_zero_capacity_uses_the_model_rule() with:
events/tests.py (in EventFormTests, test_zero_capacity_uses_the_model_rule, replaced)
def test_zero_capacity_is_shown_on_capacity(self):
form = new_event_form(capacity='0')
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['capacity'],
['Capacity must be more than 0.'])
self.assertEqual(form.non_field_errors(), [])
Then add at the end of the file:
events/tests.py (add at the end)
BELOW = ('Capacity cannot be below the places already '
'taken: 2.')
class CapacityTests(TestCase):
"""Capacity may not drop below the places taken."""
@classmethod
def setUpTestData(cls):
cls.sam = User.objects.create_superuser(
'sam@example.org', display_name='Sam'
)
cls.clinic = save_clinic(cls.sam)
for email in ('sai@example.org', 'raj@example.org'):
Registration.objects.create(event=cls.clinic,
member=member(email))
def test_zero_is_one_message_on_capacity(self):
form = edit_form(self.clinic, capacity='0')
self.assertFalse(form.is_valid())
self.assertEqual(form.errors, {
'capacity': ['Capacity must be more than 0.'],
})
self.clinic.capacity = 0
with self.assertRaises(ValidationError):
self.clinic.full_clean()
def test_below_the_places_taken_is_refused(self):
form = edit_form(self.clinic, capacity='1')
self.assertFormError(form, 'capacity', BELOW)
def test_the_admin_refuses_it_too(self):
self.client.force_login(self.sam)
response = self.client.post(
admin_url(Event, 'change', self.clinic.pk),
event_form(self.clinic, capacity=1),
)
self.assertContains(response, BELOW)
self.clinic.refresh_from_db()
self.assertEqual(self.clinic.capacity, 50)
def test_the_places_taken_are_enough(self):
soni = Registration.objects.create(
event=self.clinic,
member=member('soni@example.org'),
)
soni.status = Registration.Status.CANCELLED
soni.cancelled_at = timezone.now()
soni.save()
form = edit_form(self.clinic, capacity='2')
self.assertTrue(form.is_valid(), form.errors)
CapacityTests makes Sam a superuser, so the same account can post to the admin’s event page with Chapter 23’s event_form() helper; Sai and Raj hold two places. Run every events test, which includes both classes:
Three fail and one stops with an error. The zero message is still form-wide, and both forms accept a capacity of 1 for two places; Chapter 24’s replaced test stops with KeyError: 'capacity', because the form has no message on Capacity to look up. The fourth new test passes already: a capacity of 2 for two active places, with a cancelled one not counted, is fine.
In events/models.py, add this constant after the function validate_timezone_name(), with two blank lines before and after it:
events/models.py (after validate_timezone_name)
CAPACITY_MESSAGE = 'Capacity must be more than 0.'
In the constraint named event_capacity_gt_0, replace the three lines of violation_error_message=(...) with one line that uses it:
events/models.py (in event_capacity_gt_0, violation_error_message, replaced)
violation_error_message=CAPACITY_MESSAGE,
And add this method to Event, after places_taken():
events/models.py (Event, after places_taken)
def clean(self):
"""Check a saved event keeps room for its places.
Zero is left to the event_capacity_gt_0 rule.
"""
if self.pk is None or not self.capacity:
return
taken = self.places_taken()
if self.capacity < taken:
raise ValidationError({
'capacity': ValidationError(
'Capacity cannot be below the places '
'already taken: %(taken)s.',
code='below_places_taken',
params={'taken': taken},
),
})
Django calls a model’s clean() during full_clean(), after each field’s own checks and before the constraints, which makes it the place for a rule that needs a query. Raising ValidationError with a dictionary, {'capacity': ...}, names the field the message belongs to, so the form shows it beside Capacity, and the constraint checks then skip that field. The method leaves new events alone, because they have no places yet, and leaves 0 to Chapter 21’s constraint, so the admin still shows the message Chapter 23 printed for it. In events/forms.py, replace the line from .models import Event with:
events/forms.py (the .models import, replaced)
from .models import CAPACITY_MESSAGE, Event
And add this method to EventForm, before clean():
events/forms.py (EventForm, before clean)
def clean_capacity(self):
"""Refuse a capacity below 1 with one message."""
capacity = self.cleaned_data['capacity']
if capacity < 1:
raise ValidationError(CAPACITY_MESSAGE,
code='capacity_too_small')
return capacity
clean_capacity() runs for one field, after that field has turned the text into a number, and its message appears beside Capacity. It uses the model’s own text, so the page and the constraint can never disagree. Run the events tests again:
Terminal
uv run python manage.py test events
Output
Found 86 test(s).
Creating test database for alias 'default'...
...
Ran 86 tests in ...
OK
Destroying test database for alias 'default'...
The constraint’s message is the same text as before, so the model’s description has not changed. Check that Django agrees:
Terminal
uv run python manage.py makemigrations --check --dry-run
Output
No changes detected
Common Error: a message for a field the form does not have
A model’s clean() may name only fields that are on the form. Name a field that is not, such as {'places': ...}, and the form raises an error instead of showing a message: ValueError: 'EventForm' has no field named 'places'. Name a field the person can correct, or raise the error without a field name, so it appears at the top.
Step 7: Prove that crafted fields change nothing
The allowlist from Chapter 24 already protects the edit page. These tests make that a fact the suite checks, so a later change cannot quietly undo it: a POST with status, id, pk, and owner changes the event’s fields and nothing else; a missing field is refused, not kept from the row; and naming organizers in a POST changes no assignment. Add at the end of events/tests.py:
events/tests.py (add at the end)
class CraftedFieldTests(TestCase):
"""Fields the form lacks cannot change an event."""
@classmethod
def setUpTestData(cls):
cls.sam = editor()
cls.clinic = save_clinic(cls.sam)
cls.url = edit_url(cls.clinic)
def setUp(self):
self.client.force_login(self.sam)
def test_fields_off_the_list_change_nothing(self):
data = as_sent(self.clinic, status='published',
id='999', pk='999', owner='1')
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, 302)
event = Event.objects.get()
self.assertEqual(event.pk, self.clinic.pk)
self.assertEqual(event.status, Event.Status.DRAFT)
def test_a_missing_field_is_refused_not_kept(self):
data = as_sent(self.clinic, title='Django clinic')
del data['location']
response = self.client.post(self.url, data)
self.assertContains(response,
'This field is required.')
self.clinic.refresh_from_db()
self.assertEqual(self.clinic.title,
'Online Django clinic')
def test_editing_never_changes_organizers(self):
sai = member('sai@example.org')
data = as_sent(self.clinic, member=sai.pk,
organizer_assignments=sai.pk)
self.client.post(self.url, data)
assignments = self.clinic.organizer_assignments
organizers = [assignment.member for assignment
in assignments.all()]
self.assertEqual(organizers, [self.sam])
Terminal
uv run python manage.py test events.tests.CraftedFieldTests
Output
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...
OK
Destroying test database for alias 'default'...
They pass at once, and that is the result to expect from a test that guards a rule already in place. To see them fail, change fields in EventForm.Meta to '__all__' for a moment and run them again. The class stops before its first test, with ValueError: The Event could not be created because the data didn't validate.: the form now has a required status field, which the tests’ clinic does not send. A page that did send it would publish a draft on request, as Chapter 24’s Common Error showed. Put the list back.
Step 8: The tick box, long help, and where classes live
The page still has two rough edges. The tick box is drawn as a text box, because Chapter 24’s widget template for inputs gives every input the class input, and on a phone the “Saved:” line under Starts does not wrap, so it pushes the form wider than the screen. The test covers the tick box: one checkbox class, its label, and the zone’s help and error both linked. Add at the end of events/tests.py:
events/tests.py (add at the end)
class EditMarkupTests(TestCase):
"""The zone tick box is styled and labelled."""
@classmethod
def setUpTestData(cls):
cls.sam = editor()
cls.clinic = save_clinic(cls.sam)
def test_tick_box_is_styled_and_linked(self):
self.client.force_login(self.sam)
data = as_sent(self.clinic, timezone='Europe/London')
response = self.client.post(edit_url(self.clinic),
data)
described = ('aria-describedby="id_timezone_helptext'
' id_timezone_error"')
for text in ('class="checkbox"',
'for="id_confirm_zone"',
'aria-invalid="true"', described):
self.assertContains(response, text, count=1)
Terminal
uv run python manage.py test events.tests.EditMarkupTests
Expected result, shortened with ...:
Output
Found 1 test(s).
...
FAIL: test_tick_box_is_styled_and_linked (...)
...
AssertionError: 0 != 1 : Found 0 instances of 'class=...
...
FAILED (failures=1)
Create templates/django/forms/widgets/checkbox.html, beside Chapter 24’s two widget templates:
Django draws a tick box with the template of that name, so this one replaces Django’s, with daisyUI’s checkbox class in place of input. In templates/forms/field.html, replace the help paragraph’s opening tag so the whole file reads:
daisyUI’s label class keeps its text on one line, which was fine for Chapter 24’s short help, and Tailwind’s whitespace-normal lets a long line wrap. In static/otahque/source.css, give the tick box the same measured border as the other fields, by replacing the line .fieldset :is(.input, .select) { with:
static/otahque/source.css (the .fieldset :is(.input, .select) line, replaced)
.fieldset :is(.input, .select, .checkbox) {
Rebuild the stylesheet, as in Chapter 24:
Terminal
npm run build
Expected result, shortened with ...:
Folder structure
> build
> npm run css -- -o static/otahque/site.css
...
/*! 🌼 daisyUI 5.7.50 */
Done in ...
Terminal
uv run python manage.py test events.tests.EditMarkupTests
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...
OK
Destroying test database for alias 'default'...
Open the edit page at a phone’s width, in your browser’s device toolbar, and choose another zone again: the help lines wrap inside the form, and the tick box is a small square with a dark border. Choose the clinic’s zone again before you leave.
Chapter 24 put Otahque’s classes in templates rather than in Python. Django offers two places in Python as well, and the choice matters once a form is used on many pages. Meta.widgets, which Chapter 24 used for the two date-and-time boxes, sets a widget once, when the class is defined. Code in __init__(), such as this chapter’s tick box, runs for each form, and can depend on the event, the person, or what was sent. Create practice/widgets.py:
../practice/widgets.py
import setup_django
from events.forms import EventForm
first = EventForm()
first.fields['title'].widget.attrs['class'] = 'changed'
second = EventForm()
print(first.fields['title'].widget.attrs)
print(second.fields['title'].widget.attrs)
print(EventForm.base_fields['title'].widget.attrs)
A change to one form’s widget stays in that form: Django copies the class’s fields and widgets for every form it creates. So __init__() is safe for anything that depends on one request, and templates remain the place for classes, because Tailwind reads only templates. Writing many classes in Python attributes, a common suggestion in Django’s community, soon becomes hard to keep in step, and Tailwind would not see them.
One limit remains, and the design note records it. Create practice/two_pages.py, which plays two organizers who open the clinic’s edit page at the same time:
../practice/two_pages.py
import setup_django
from django.db import transaction
from events.forms import EventForm
from events.models import Event
def page_for(event):
"""Return what an organizer's edit page first holds."""
form = EventForm(instance=event)
return {'title': event.title,
'timezone': event.timezone,
'starts_at': form.shown['starts_at'],
'ends_at': form.shown['ends_at'],
'location': event.location,
'capacity': event.capacity}
def save(sent):
clinic = Event.objects.get(title='Online Django clinic')
form = EventForm(sent, instance=clinic)
form.is_valid()
changed = 'location' in form.changed_data
print('location changed?', changed)
form.save()
with transaction.atomic():
clinic = Event.objects.get(title='Online Django clinic')
first = page_for(clinic)
second = page_for(clinic)
save(first | {'location': 'Room 1'})
save(second | {'capacity': '40'})
clinic.refresh_from_db()
print(clinic.location, clinic.capacity)
transaction.set_rollback(True)
page_for() returns what an organizer’s page holds when it opens. The first organizer changes the location; the second, from the older page, changes the capacity. The second save writes the old location back, so the result keeps the second capacity and loses the first location. Note the second “True”: compared with the row as it is now, the old location counts as a change, so saving only the changed fields would not protect the first organizer either. Only a token that the page carries, such as a version number, can tell the server which version the person saw. That needs a new field, so Chapter 33 adds it, and the file rolls back everything it did.
Step 9: Prove CSRF on the edit page, record the design, and commit
The edit page changes data, so it needs the same proof as the New event page: a client that enforces the CSRF check is refused without a token, and accepted with the page’s token. Add at the end of events/tests.py:
events/tests.py (add at the end)
class EditCsrfTests(TestCase):
"""An edit without the CSRF token is refused."""
@classmethod
def setUpTestData(cls):
cls.sam = editor()
cls.clinic = save_clinic(cls.sam)
def test_an_edit_without_the_token_is_refused(self):
browser = Client(enforce_csrf_checks=True)
browser.force_login(self.sam)
url = edit_url(self.clinic)
data = as_sent(self.clinic, title='Forged')
refused = browser.post(url, data)
self.assertEqual(refused.status_code, 403)
self.clinic.refresh_from_db()
self.assertEqual(self.clinic.title,
'Online Django clinic')
token = str(browser.get(url).context['csrf_token'])
saved = browser.post(
url, data | {'csrfmiddlewaretoken': token}
)
self.assertEqual(saved.status_code, 302)
Terminal
uv run python manage.py test events.tests.EditCsrfTests
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...
OK
Destroying test database for alias 'default'...
It passes at once, because the middleware and the template’s {% csrf_token %} were already there; without the middleware it fails with AssertionError: 302 != 403. Now update the design note, docs/design/event-draft-form.md, to cover editing. Replace its contents with:
docs/design/event-draft-form.md
# Event form: low-level design
Status: Drafted in Chapters 24 and 25, for review.
Who: members with events.add_event create drafts;
current organizers with events.change_event edit them.
Visitors cannot propose events.
## Request path
- GET /events/new/: login_required, then
permission_required(add_event, raise 403); an unbound
EventForm; events/form.html.
- POST /events/new/: the same checks; CsrfViewMiddleware
refuses a missing or wrong token with 403 first.
EventForm(request.POST).is_valid():
- invalid: the same page, status 200, messages beside
the fields, typed values kept, nothing saved;
- valid: in one transaction, form.save() (status
draft, as status is not a field) and
event.add_organizer(user); message "Draft saved.";
302 to the event page (Post/Redirect/Get).
- GET /events/<id>/: Event.is_visible_to(user):
published for all; otherwise holders of view_event
and current organizers; 404 for everyone else. An
Edit event link for can_be_edited_by(user).
- GET and POST /events/<id>/edit/: login_required;
404 unless is_visible_to(user); 403 unless
can_be_edited_by(user) (change_event and a current
assignment). EventForm(request.POST, instance=event):
- invalid: 200, typed values kept, heading from the
title read before validation, nothing saved;
- valid: form.save(); "Changes saved."; 302 to the
event page.
## Who may edit
| Person | Sees event | Edit page |
|---|---|---|
| Visitor | Published only | Sent to sign in |
| Member, no change_event | Published only | 403 or 404 |
| Staff, change_event, no assignment | All | 403 |
| Current organizer, change_event | All | Form |
## Validation layers, in the order they run
1. Fields: required values, lengths, whole numbers,
the zone from the list.
2. clean_capacity(): 0 refused on Capacity.
3. EventForm.clean(): times read in the event's zone,
except a time left as shown in an unchanged zone,
which keeps its stored value; clock-change times
refused; ends after starts, on Ends; a new zone
needs the confirm_zone box, with both readings.
4. Model full_clean(): validate_timezone_name;
Event.clean() refuses a capacity below the active
registrations; Chapter 21's constraints.
5. Database: Chapter 21's constraints refuse a bad
row from anywhere.
## Limits and later work
- Sign-in is the admin's page until Chapter 27, so
only staff can sign in through a browser.
- Members holding places are not told of changes;
the edit page says so. Open until Chapters 43-44.
- Last save wins: two organizers editing at once can
undo each other. Chapter 33 adds a version check.
- The capacity floor reads, then writes; Chapter 33
adds the lock that closes the gap.
- Publishing is Chapter 26.
- Once Chapter 28 activates each viewer's zone, clean
the times under the event's zone instead.
- Widget templates copy Django 6.1's; check them when
Django is upgraded.
The file keeps its name, which Chapter 24 used, and now describes both pages. Its table is the access rule of Figure 25.2, and its last section lists what this chapter leaves for later. Run every test:
Terminal
uv run python manage.py test
Expected result, shortened with ...:
Output
Found 124 test(s).
Creating test database for alias 'default'...
...
Ran 124 tests in ...
OK
Destroying test database for alias 'default'...
Confirm that no model change needs a migration:
Terminal
uv run python manage.py makemigrations --check --dry-run
Output
No changes detected
Stage the work and look at what will be committed:
Terminal
git add docs events static templates
git status --short
Output
M docs/design/event-draft-form.md
M events/forms.py
M events/models.py
M events/templates/events/detail.html
A events/templates/events/edit.html
M events/tests.py
M events/urls.py
M events/views.py
M static/otahque/site.css
M static/otahque/source.css
A templates/django/forms/widgets/checkbox.html
M templates/forms/field.html
Terminal
git commit -m "Add the edit event page"
Table 25.2 — When something goes wrong in Chapter 25
Symptom
Likely cause
Recovery
NoReverseMatch for 'events:edit'
The address is missing or misspelt in events/urls.py
Compare with Step 3's line; keep name='edit'
Sai gets 403 for a draft
The edit check runs before is_visible_to()
Check visibility first, as in Step 3's view
Starts shows midnight, 5 hours off
show_saved_times() missing or not called
Compare __init__() with Step 4
A saved edit moved the event
The page's text and self.shown differ
Run EditFormTests; compare read_time()
Heading shows the typed title
The view reads event.title after binding
Read title = event.title first
Saving made a second event
instance=event missing on the POST form
Pass instance= to both forms
ValueError: no field named ...
Model clean() names a field not on the form
Name capacity, or raise without a field
Tick box drawn as a text box
checkbox.html missing or misnamed
Check templates/django/forms/widgets/
Help pushes the page sideways
whitespace-normal missing, or no rebuild
Check field.html; run npm run build
Anything else
A difference from the chapter's files
Compare with a fresh clone of your Chapter 24 commit; do not reset your work
Work through Table 25.3 from the folder that holds manage.py. The test rows come first: they hold the page’s rules in place, whatever rows your database holds.
Table 25.3 — Verification checklist for Chapter 25
The commands were checked in Windows PowerShell 5.1 and Git Bash, and the browser rows in Microsoft Edge against the development server, at a phone’s width in the Asia/Kolkata zone and a desktop’s in the America/New_York zone. The edit page shows the same times in both, because it reads the event’s zone, not the browser’s.
Que. 3 After form = EventForm(request.POST, instance=event) and form.is_valid() returns false, what does event.title hold, and what is stored?
Flip to check your answerFold answer back
Answer. event.title holds the title Sam typed, because is_valid() copies the cleaned values onto the instance before the model’s checks run. The stored row is unchanged, because nothing called save(). That is why the view reads the title before binding the form.
Que. 4 In which order do these run for an edit: the model’s clean(), the form’s clean(), clean_capacity(), and validate_constraints()?
Flip to check your answerFold answer back
Answer. clean_capacity(), then the form’s clean(), then the model’s clean(), then validate_constraints(). Field rules come first, then the form’s rules across fields, then the model’s checks, with the constraints last.
Que. 5 An administrator holds view_event and change_event but organizes no event. What do they get on Sam’s draft’s edit page, and where do they edit events instead?
Flip to check your answerFold answer back
Answer. 403 Forbidden: they may see the draft, through view_event, but can_be_edited_by() also needs a current organizer assignment. They edit events in the admin site, the administrator’s tool since Chapter 23.
Que. 6 Two members hold places at Sam’s clinic. Which layer refuses a capacity of 1, and which refuses 0? Where does each message appear?
Flip to check your answerFold answer back
Answer. The model’s clean() refuses 1, because it is below the two places taken, and the form shows the message beside Capacity. The form’s clean_capacity() refuses 0, also beside Capacity; behind both, the database’s constraint refuses 0 from anywhere.
Que. 7 Why does the form compare the text that comes back with self.shown instead of using form.changed_data?
Flip to check your answerFold answer back
Answer. changed_data compares the sent text with the initial value read in UTC, so it reports both times as changed even when Sam touched neither. The form knows the exact text it showed, so comparing text is exact, and it avoids reading a repeated hour again.
Mini-Challenge
Que. 8 Predict what the form does with three edits of Sam’s clinic, each sent with the clinic’s other values unchanged: the zone set to Asia/Kolkata; the same with the tick box ticked; and the start moved to 18:00 with the zone kept. For each valid one, give the start as the form will store it, with its offset from UTC. Then check with a practice file that only validates, so nothing is saved.
Flip to check your answerFold answer back
Answer. The first is refused, with the code zone_changed, because a new zone needs the tick box. The second is valid, and the start is 19:00 on 3 December in Kolkata, +05:30, which is 13:30 UTC. The third is valid: 18:00 on 3 December in New York, -05:00. One file that checks it, run with uv run python ../practice/challenge.py:
../practice/challenge.py
import setup_django
from events.forms import EventForm
from events.models import Event
SENT = {'title': 'Online Django clinic',
'timezone': 'America/New_York',
'starts_at': '2026-12-03T19:00',
'ends_at': '2026-12-03T20:30',
'location': 'Online', 'capacity': '50'}
EDITS = [{'timezone': 'Asia/Kolkata'},
{'timezone': 'Asia/Kolkata', 'confirm_zone': 'on'},
{'starts_at': '2026-12-03T18:00'}]
for edit in EDITS:
clinic = Event.objects.get(title='Online Django clinic')
form = EventForm(SENT | edit, instance=clinic)
if form.is_valid():
starts = form.cleaned_data['starts_at']
print('valid, starts', starts.isoformat())
else:
error = form.errors.as_data()['timezone'][0]
print('refused:', error.code)
isoformat() writes a date and time with its offset. The file sends 20:30 for Ends, not the 21:00 you saved in Step 5, so the form reads that time again; the three results are the same either way. The file calls no save(), so your rows are unchanged.
What We Learned
EventForm(request.POST, instance=event) edits one row with the same fields and rules as creating it; save() updates that row.
is_valid() runs field rules, clean_<name>(), the form’s clean(), copies values onto the instance, then the model’s clean_fields(), clean(), unique checks, and constraints; only save() writes.
The instance changes even when the form is invalid, so read saved values before binding.
Model permissions answer “may this person change events?”; an ownership check answers “this event?”. Check visibility first: 404 for the hidden, 403 for the refused.
Show stored times in the event’s zone, keep text that was not changed, and confirm a change of zone with both readings shown together.
A rule across two tables, such as capacity against places taken, lives in the model’s clean(), so every ModelForm, the admin’s included, obeys it; a lock comes in Chapter 33.
The allowlist protects edits too, and tests that pass at once can guard a rule that is already in place.
The last save wins until Chapter 33 adds a version check.
Key terms
Use Table 25.4 to explain this chapter’s ideas in your own words.
Table 25.4 — Key terms from Chapter 25
Term
Meaning
instance=
The saved object a ModelForm starts from and updates.
Validation lifecycle
The order is_valid() checks in: fields, form, instance, model.
clean_<name>()
A form method that adds a rule to one field.
_post_clean()
The ModelForm stage that copies values onto the instance and runs the model's checks.
Model clean()
The model method for rules that need more than one field or a query.
commit=False
save() without writing, for setting values the form does not own.
Object-level check
A rule about one object, such as "organizes this event".
403 and 404
Refused, and not found: 404 hides what the person may not see.
Initial value
What a box shows before anything is typed.
Lost update
A later save that silently undoes an earlier one.
Version check
Refusing a save made from an older version of a row.
Readiness checkpoint: you are ready for Chapter 26 when all 124 tests pass, makemigrations --check --dry-run prints No changes detected, signing in as Sam shows Edit event on the clinic’s page, the edit page shows its times in New York with the saved line, a changed end is saved with “Changes saved.”, a changed zone alone is refused with both readings, and git status --short prints nothing. Chapter 26 publishes a draft once it is ready. Return to the relevant step if any result is missing.
Git Commit
Your Chapter 25 work was committed in Step 9. For the record, these were the commands, in any of the four shells, beside manage.py:
Terminal
git add docs events static templates
git status --short
Output
M docs/design/event-draft-form.md
M events/forms.py
M events/models.py
M events/templates/events/detail.html
A events/templates/events/edit.html
M events/tests.py
M events/urls.py
M events/views.py
M static/otahque/site.css
M static/otahque/source.css
A templates/django/forms/widgets/checkbox.html
M templates/forms/field.html
Terminal
git commit -m "Add the edit event page"
The commit holds the edit view, its address and template, four model methods, the capacity message as one constant, the form’s saved times, kept times, zone confirmation, and capacity rule, the link on the event page, the tick box template, the wrapping help, the rebuilt stylesheet, twenty-seven new tests and one changed, and the design note. There is no migration, because no field changed.
These five questions rehearse the chapter at interview level, one at each of five levels from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead to a larger application with a team: attempt them now, and return to them after Chapters 30 and 33. They are extension questions, not a gate to the next chapter. Each code proof is a short file in the practice folder that starts by importing Chapter 16’s setup_django.py; run it from the folder that holds manage.py with uv run python ../practice/ followed by the file name. The proofs only read your rows: any row they create is rolled back.
L1 (Junior): What does a ModelForm do between is_valid() and save()?
What the interviewer is testing: Do you know the validation lifecycle, and what has and has not happened to the object and the database before save()?
Flip to check your answerFold answer back
Perfect answer:is_valid() runs the whole lifecycle once. Each field converts and checks its text, then any clean_<name>() method adds a rule for that field. The form’s clean() checks rules across fields. Then the ModelForm copies the cleaned values onto the instance and runs the model’s full_clean(): field validators, the model’s clean(), unique checks, and constraints, skipping checks for fields that have already failed. Every message lands in errors, beside a field or at the top. Nothing is written: the instance in memory has changed, valid or not, and the row in the database has not. save() writes it, or save(commit=False) returns it unsaved so I can set something the form does not own. In Otahque, Sam’s typed title is on the event after is_valid(), and still not in the database.
Table 25.5 — Before and after save()
Moment
The instance
The row
Before is_valid()
Saved values
Saved values
After is_valid()
Typed values, even if invalid
Saved values
After save()
Typed values
Typed values
Behind the scenes:
the lifecycle of one edit (summary)
fields, clean_<name>() -> each value
form clean() -> values together
_post_clean() -> copy onto instance
model full_clean() -> model rules, constraints
save() -> the only write
Code proof: Sam’s clinic, after a valid is_valid() and before save():
True Django clinic
stored: Online Django clinic
times kept: True
The form is valid and the instance already holds “Django clinic”, while the stored row still says “Online Django clinic”. The start was left as shown, so the cleaned start is exactly the stored one.
Common mistakes:
Believing is_valid() leaves the instance alone, and showing it after a failure.
Thinking a constraint runs before the form’s clean().
Using commit=False and forgetting to save the instance.
Follow-up the interviewer might ask:
“Where would you put a rule that needs a query, and why?”
“When do you need save_m2m()?”
L2 (Mid-Level): Two members hold places. Sam sets capacity to 1, then to 2. Predict each response and what is saved.
What the interviewer is testing: Can you trace a rule that spans two tables through the lifecycle, and say exactly where its message appears and what reaches the database?
Flip to check your answerFold answer back
Figure 25.6 — How the capacity floor answers 1 and 2.
Perfect answer: With 1, the field converts the text to the number 1, and clean_capacity() passes, because 1 is more than 0. The form’s clean() passes too. The ModelForm copies 1 onto the event and runs the model’s clean(), which counts the active registrations, two, and raises a ValidationError naming capacity: “Capacity cannot be below the places already taken: 2.” The form shows it beside Capacity, is_valid() is false, the view returns the page with status 200 and Sam’s other values, and nothing is saved. With 2, every stage passes, a cancelled registration is not counted, save() updates the row, and the response is a redirect to the event page with “Changes saved.” The same rule refuses 1 in the admin, because the admin’s form runs the model’s clean() as well.
Behind the scenes:
capacity 1, two places (summary)
field -> 1
clean_capacity() -> passes: more than 0
model clean() -> 2 taken: error on capacity
is_valid() False -> 200, same page, no save()
Code proof: two registrations, made and rolled back inside a transaction:
../practice/l2_capacity.py
import setup_django
from django.db import transaction
from accounts.models import User
from events.forms import EventForm
from events.models import Event
from registrations.models import Registration
with transaction.atomic():
clinic = Event.objects.get(title='Online Django clinic')
for email in ('sai@example.org', 'raj@example.org'):
member = User.objects.get(email=email)
Registration.objects.create(event=clinic,
member=member)
for capacity in ('1', '2'):
clinic = Event.objects.get(pk=clinic.pk)
form = EventForm({
'title': clinic.title,
'timezone': clinic.timezone,
'starts_at': '2026-12-03T19:00',
'ends_at': '2026-12-03T20:30',
'location': clinic.location,
'capacity': capacity,
}, instance=clinic)
valid = form.is_valid()
errors = form.errors.get('capacity', ['valid'])
print(capacity, valid, errors[0])
transaction.set_rollback(True)
Output
1 False Capacity cannot be below the places already taken: 2.
2 True valid
Common mistakes:
Putting the floor only in Otahque’s form, so the admin can still lower capacity.
Counting every registration, cancelled ones included.
Claiming the check prevents a race: a registration can arrive between the count and the save.
Follow-up the interviewer might ask:
“How would you stop a registration slipping in between the count and the save?”
“Why not a database CHECK for this rule?”
L3 (Senior): The form already refuses a capacity of 0. Defend keeping the database constraint.
What the interviewer is testing: Do you understand layered validation, and which layer is the last line rather than the friendly message?
Flip to check your answerFold answer back
Figure 25.7 — Why the constraint stays when the form checks first.
Perfect answer: Each layer covers a different way in. The form’s clean_capacity() exists for people: it explains the rule beside the field, in words Sam understands. The model’s validation covers every ModelForm, the admin’s included. But code can write rows without either: QuerySet.update(), bulk_create(), a data migration, a management command, or someone in the shell. Only the database sees every write. Chapter 21’s constraint is that last line, so a bug in a later script cannot store an event with no places. The cost is small: one CHECK, already written. To keep the layers from disagreeing, the form reuses the constraint’s message, through one constant, so they can never say different things.
Behind the scenes:
who checks capacity (summary)
clean_capacity() -> the page: friendly message
model full_clean -> ModelForms, the admin
database CHECK -> everything: update(), shell
Code proof: the model’s check and the database, both bypassing the form:
../practice/l3_backstop.py
import setup_django
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
from events.models import Event
clinic = Event.objects.get(title='Online Django clinic')
clinic.capacity = 0
try:
clinic.full_clean()
except ValidationError as error:
print('full_clean():', error.messages[0])
try:
with transaction.atomic():
Event.objects.filter(pk=clinic.pk).update(capacity=0)
except IntegrityError as error:
print('update():', type(error).__name__)
print('stored:', Event.objects.get(pk=clinic.pk).capacity)
Output
full_clean(): Capacity must be more than 0.
update(): IntegrityError
stored: 50
full_clean() reports the constraint’s message, update() skips Python entirely and is refused by the database, and the stored capacity is unchanged.
Common mistakes:
Dropping the constraint because “the form already checks it”.
Writing the message twice, so the page and the database drift apart.
Catching IntegrityError and showing it to people instead of validating first.
Follow-up the interviewer might ask:
“Which writes skip full_clean() in Django?”
“How would you add such a constraint to a table that already has bad rows?”
L4 (Staff): Organizers report that saving an edit, without changing anything, moved their event by five hours. Diagnose and fix it.
What the interviewer is testing: Can you find a round-trip bug between display and input, prove it with a failing test, and fix it without breaking edge cases?
Flip to check your answerFold answer back
Figure 25.8 — From a report of moved events to a tested fix.
Perfect answer: I would compare what the page shows with what the form reads. Django writes a stored time into a box in the current zone, UTC, so a 19:00 New York event shows 00:00 on the next day. On save, the form reads the text in the event’s zone, as it must for typed times, so 00:00 becomes 00:00 in New York: five hours later than stored. Every unchanged save moves the event. First I write a failing test that sends the edit page back exactly as shown and expects the same instant. The fix has two parts: show stored times converted to the event’s zone, and keep the stored instant when the zone and the text are unchanged. The second part also keeps seconds the box cannot show, and an event in a repeated clock hour, which reading the text again would refuse. I would also check the data: events edited since the bug shipped may already have moved.
Behind the scenes:
one unchanged save (summary)
stored -> 00:00 UTC, 4 December
shown in UTC -> 2026-12-04T00:00
read in New York -> 05:00 UTC: moved 5 h
shown in zone -> 2026-12-03T19:00: kept
Code proof: the same clinic, sent back first with UTC text, then with the text the page shows:
../practice/l4_drift.py
import setup_django
from events.forms import EventForm
from events.models import Event
clinic = Event.objects.get(title='Online Django clinic')
NAMES = ('starts_at', 'ends_at')
in_utc = {name: f'{getattr(clinic, name):%Y-%m-%dT%H:%M}'
for name in NAMES}
in_zone = EventForm(instance=clinic).shown
for label, texts in (('UTC text', in_utc),
('zone text', in_zone)):
clinic = Event.objects.get(pk=clinic.pk)
before = clinic.starts_at
form = EventForm({
'title': clinic.title, 'timezone': clinic.timezone,
'location': clinic.location, 'capacity': '50',
} | texts, instance=clinic)
form.is_valid()
moved = form.cleaned_data['starts_at'] - before
print(label, texts['starts_at'], 'moved by', moved)
Output
UTC text 2026-12-04T00:00 moved by 5:00:00
zone text 2026-12-03T19:00 moved by 0:00:00
Common mistakes:
Setting the server’s TIME_ZONE to New York, which breaks every event in another zone.
Using changed_data, which reports both times as changed.
Fixing the display and forgetting the events already moved.
Follow-up the interviewer might ask:
“How would you find the events the bug already moved?”
“What changes when Chapter 28 shows each viewer their own zone?”
L5 (Lead): A manager wants any staff account to edit any event from Otahque’s own pages. What do you advise?
What the interviewer is testing: Can you weigh convenience against a written rule, and offer a safe path rather than a flat no?
Flip to check your answerFold answer back
Figure 25.9 — Weighing a request to let any staff account edit any event.
Perfect answer: I would ask what problem they are solving: usually, fixing a mistake while the organizer is away. Otahque’s requirement PR-4 says organizers manage only the events assigned to them, and today the edit page enforces it: change_event and a current assignment, both. Staff already have a tool for exceptions, the admin site, which records each change in its history. Letting every staff account edit every event on Otahque’s pages would make PR-4 false, widen what one stolen staff account can change, and blur who answers for an event. If the need is real, I would offer to assign a staff member as an organizer of that event, which is recorded and can be revoked, and design proper roles in Chapter 30. If the manager still wants the change, it is a requirement change: update PR-4, then change can_be_edited_by() and its tests together.
Behind the scenes:
who may edit (summary)
change_event alone -> the admin site
plus assignment -> Otahque's edit page
assignment -> recorded, revocable
rule change -> PR-4 first, then code
Code proof: Sam and a staff account that holds change_event but organizes nothing, made and rolled back:
../practice/l5_staff.py
import setup_django
from django.contrib.auth.models import Permission
from django.db import transaction
from accounts.models import User
from events.models import Event
with transaction.atomic():
clinic = Event.objects.get(title='Online Django clinic')
staff = User.objects.create_user(
'staff@example.org', display_name='Staff',
is_staff=True,
)
staff.user_permissions.add(Permission.objects.get(
codename='change_event'))
staff = User.objects.get(pk=staff.pk)
sam = User.objects.get(email='sam@example.org')
for person in (sam, staff):
print(person.email,
person.has_perm('events.change_event'),
clinic.has_organizer(person),
clinic.can_be_edited_by(person))
transaction.set_rollback(True)