Chapter 24 · Django forms: Sam's first event, typed on Otahque's own pageCHAPTER 24
Complete six-part pre-release for review. Editing drafts is Chapter 25 and publishing Chapter 26; until Chapter 27, signing in uses the admin's sign-in page. 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-FOUR
Django forms: Sam's first event, typed on Otahque's own page
Stage 4: Accounts and first release (Chapters 24 to 34)
Prerequisites: Chapters 15 to 23, including the Chapter 23 project, its 77 passing tests, the admin site at your DJANGO_ADMIN_URL, and the superuser account you created for Sam in Chapter 18
What you’ll build: A New event page where Sam types an event’s title, time zone, start, end, location, and capacity; a form that reads the times in the event’s own zone, refuses times that a clock change skips or repeats, keeps everything he typed when something is wrong, and saves only a draft; a draft page that only the event’s organizers and the administrator can open; accessible, styled fields; and twenty tests, including Otahque’s first test that a forged request is refused.
Why This Matters
Since Chapter 19, every event in Otahque has been typed by you, in the shell or, since Chapter 23, in the admin site. Neither is a place for Sam. The shell is for developers, and Chapter 23 decided that the admin site is the administrator’s tool: it reads every typed time in UTC, it lets an account with one permission change every event, and it has no idea that Sam organizes only his own. Sam needs a page of Otahque’s own where he can describe an event, see each mistake explained beside the field it belongs to, and save it without anyone else seeing it before it is ready.
Sam lives in India, and his next event is an online Django clinic for a group in the United States, at 19:00 New York time on 3 December. A page that reads his 19:00 in UTC stores a time five hours early; one that reads it in his own zone stores it ten and a half hours early. The time means what the event’s zone says it means, so the form must read it there, and it must say so on the page. And whatever the form allows, it must never let a typed value set something Sam should not control, such as whether the event is published.
That is what forms are for. A form is the part of a web page where people type values and send them to the server, and Django’s form library is the part of Django that checks those values, explains what is wrong, and hands your code clean, typed values. This chapter builds Otahque’s first one: Sam’s New event page, which saves a draft. Visitors cannot propose events; a visitor still only reads published ones.
By the end of the chapter, you will be able to:
explain how a browser sends a form, and what Django does between the request and your view’s first line;
write a Form and a ModelForm, and say why a ModelForm’s fields list is an allowlist;
decide where each rule lives: a field, the form’s clean(), the model, or the database;
read typed times in the event’s own time zone, and refuse a time that a clock change skips or repeats;
protect a page with sign-in, a permission, and an ownership check, and show a draft only to the people who may see it;
render fields with labels, help text, and errors that browsers and screen readers connect, and prove the protection against forged requests with a test.
Editing a draft and the form’s validation in depth are Chapter 25, publishing Chapter 26, and members’ own sign-in pages Chapter 27. Showing each viewer times in their own zone is Chapter 28, and the design of roles and permissions Chapter 30.
Every page you have built so far answers a GET request: the browser asks for an address, and the view returns a page. A GET request should never change anything on the server, because browsers, search engines, and link previews send them freely. A form that changes data uses POST instead.
New Concept: HTML forms and POST
What problem exists? A person needs to send values to the server, such as an event’s title and start, and the server must know they are a request to change something, not a request to read.
What did people do before? Early sites put values in the address, as ?title=Clinic, which every link preview and browser history then repeated, and which anyone could change by editing the address bar.
What is it? An HTML <form> element holds input elements, each with a name. When the person presses its button, the browser sends one request to the form’s address with each name and the value typed into it. With method="post", the values travel in the request’s body, and Django gives them to the view as request.POST, a dictionary-like object whose values are always text.
Why use it? POST tells everyone along the way that the request changes something, so browsers warn before sending it twice, and caches and previews leave it alone.
Now let’s use it. Step 5 writes the New event page’s <form method="post">, and Step 6 handles what it sends.
The whole journey of Sam’s new event is in Figure 24.1. The view handles both requests at one address, /events/new/. A GET returns the page with an empty form. A POST carries what Sam typed: if anything is wrong, the view returns the same page with the errors and with every value he typed; if everything holds, it saves the draft and answers with a redirect, a response that tells the browser to request another address, here the event’s own page. The browser then asks for that page with GET. This pattern is called Post/Redirect/Get: because the last request is a GET, refreshing the page, or pressing Back, can never send the form a second time and save the event twice.
Figure 24.1 — One address, two methods: a GET shows the form, and a POST either returns it with errors or saves and redirects.
Django’s Form class
Turning request.POST into something your code can trust takes work: every value is text, any can be missing, and each needs checks and a message a person understands. Django’s form library does that work.
New Tool: Django forms
What problem exists? Each value a person sends must be checked, converted from text, explained when it is wrong, and shown again so they can correct it, and the HTML for the inputs must match the checks.
What did people do before? They wrote the checks and the HTML by hand for every form, as The Custom Way below does, and the two drifted apart.
What is it? A form class, a subclass of django.forms.Form, lists fields, such as forms.CharField, each of which knows how to check and convert one value and how to draw its input with a widget, the object that writes the HTML for an input. An instance of the class is unbound when it holds no data, and bound when you give it data, such as request.POST.
Why use it? One class describes the checks and the HTML together, and Django supplies the messages, the conversions, and the rendering.
Now let’s use it. Step 2 creates a form in a practice file and asks it each question in Table 24.1.
Table 24.1 — What a form can tell you
Attribute or method
What it answers
is_bound
Was the form given data, or is it an empty form for a GET?
is_valid()
Do all the values pass every check? Runs the checks the first time it is called
errors
The messages, by field name; __all__ holds those that belong to no single field
data
What was sent, as text, exactly as the browser sent it
cleaned_data
The checked, converted values, such as a number or a date and time; only after is_valid()
non_field_errors()
The messages that belong to the whole form
The difference between data and cleaned_data is the one to keep. data['capacity'] is the text '50'; cleaned_data['capacity'] is the number 50. Code after is_valid() reads cleaned_data only, never request.POST, because only those values have passed every check.
Under the Hood: what is_valid() runs
is_valid() calls the form’s full_clean() once and returns whether errors is empty. full_clean() works through the fields in order: each field’s clean() converts the text and runs its validators, such as “required” and a maximum length, and stores the value in cleaned_data or the message in errors; then a method named clean_ followed by the field’s name runs, if the form has one. When every field is done, the form’s own clean() runs, for rules that need more than one value. For a ModelForm, one more stage follows: Django copies the cleaned values onto a model instance and calls the model’s validation, the full_clean() that Chapter 21 wrote rules for, with its field validators and its constraints, and any message the model raises joins errors. Nothing is written to the database by any of this; save() does that, and only you call it.
ModelForm: a form from the model, and its allowlist
Otahque’s Event model already lists the fields an event has, their kinds, and their rules. Writing a Form that repeats them would leave two copies to keep in step. A ModelForm builds its fields from the model instead, as the admin’s forms did in Chapter 23, and its save() creates or updates the model’s row.
A ModelForm needs to know which of the model’s fields to include, in an inner class called Meta. Its fields list is an allowlist: only the fields named in it are on the form, and only they can be set by what a browser sends. That is the safety rule of this chapter. The Event model has a status field, and Sam must not be able to publish an event by sending status=published, from a tampered browser or a script. Leaving status out of fields means a posted status value is ignored, and the model’s default, draft, is saved. Django’s documentation strongly recommends naming the fields explicitly: fields = '__all__' or a list of exclusions would quietly add any field the model gains later, such as an owner or a price.
Where each rule lives
Otahque’s event rules now have four possible homes, and each catches different mistakes. Figure 24.2 shows them in the order they run.
Figure 24.2 — Four layers check Sam’s event; the first three explain, and the database refuses whatever slips past.
A field checks one value alone. The form’s clean() checks rules that compare fields, written for this page. The model’s validation holds the rules that apply wherever an event is saved through a form, the admin’s included. The database’s constraints, from Chapter 21, refuse a bad row however it arrives, from a form, the shell, or a script, but a refusal there is an error page, not a message. So each rule lives in the lowest layer that can state it, and is repeated above only when a person needs a better message. In this chapter, “ends after it starts” is checked in the form’s clean(), so its message appears beside the Ends field, while the database constraint stays as the backstop. “Capacity must be more than 0” stays in the model, and its message appears at the top of the form; Chapter 25 discusses moving such messages beside their field.
Times typed in the event’s own zone
Chapter 23 showed that Django reads a typed time in the current time zone, UTC in Otahque, so 15:00 typed for the Kolkata workshop became 15:00 UTC. Sam’s form fixes that for his page: it reads the times in the zone chosen for the event. Figure 24.3 follows his clinic from the text the browser sends to the instant that is stored.
Figure 24.3 — The same typed text means a different instant in each zone, so the form reads it in the event’s.
Two more things make a typed time tricky. A clock change moves local time forward or back by an hour in many zones. When New York’s clocks go forward at 02:00 on 14 March 2027, the times from 02:00 to 02:59 do not exist that day; when they go back at 02:00 on 1 November 2026, the times from 01:00 to 01:59 happen twice. A form that guessed would store an event an hour away from what Sam meant, so Otahque’s form refuses those times and says why. The second is choosing the zone at all: the form asks for it in a list, and a small script fills in the zone the browser reports, so Sam usually leaves it alone. When the event’s audience is elsewhere, as with his New York clinic, he chooses another.
Who may open the page, and who may see a draft
Chapter 23 introduced Django’s model permissions. This page uses two of them. events.add_event lets an account create events, so the page is open only to signed-in people who hold it. events.view_event lets the administrator read every event, drafts included. And when Sam saves a draft, Otahque records him as its organizer with Chapter 20’s OrganizerAssignment, so the draft’s page can be shown to its organizers. Figure 24.4 lists who sees what.
Figure 24.4 — Who may create events, and who may see a draft.
Two decorators, functions that wrap a view, do the page’s checks. login_required sends anyone who is not signed in to the address in the LOGIN_URL setting, with ?next= holding the page they asked for. permission_required refuses a signed-in account without the permission, with status 403. Otahque has no sign-in page for members yet; Chapter 27 builds one. Until then, LOGIN_URL points at the admin’s sign-in page, which only staff accounts can use. That is enough on your computer, where you sign in as Sam, your Chapter 18 superuser. It also means a member who is not staff, given add_event, could not sign in through the browser before Chapter 27; the tests sign such members in directly.
Forged requests, and the CSRF token
A signed-in browser sends its session cookie with every request to Otahque, whichever page caused the request. That is what makes forms dangerous.
New Concept: cross-site request forgery (CSRF)
What problem exists? Another site can contain a hidden form that posts to /events/new/. If Sam visits that site while signed in to Otahque, his browser sends the form with his cookie, and Otahque would see a request from Sam.
What did people do before? Sites trusted the cookie, or checked where a request came from with headers that were easy to lose.
What is it?Cross-site request forgery is that attack. Django’s defence is a secret CSRF token: CsrfViewMiddleware, which your settings have had since Chapter 6, puts a token in a cookie, the template tag {% csrf_token %} writes it into the form as a hidden input named csrfmiddlewaretoken, and the middleware refuses any POST whose token is missing or wrong with status 403. Another site cannot read the token, so it cannot forge the request.
Why use it? It is on by default and costs one tag in each form.
Now let’s use it. Step 5 puts the tag in the form, and Step 9 proves the refusal with a test.
There is a trap for tests. Django’s test client skips the CSRF check by default, so that tests can post without fetching a token first. A test suite can therefore pass with the protection switched off. The one test that matters creates its client with enforce_csrf_checks=True, posts without a token, and expects 403.
Rendering fields people can use
A field is usable when everyone can tell what it is for, what is wrong with it, and how to fix it. That means a <label> element whose for names the input’s id, so clicking the label focuses the box and a screen reader announces the label with the box; help text and error messages that the input points to; and a sign that a value is wrong that does not depend on colour alone.
Django 6.1 does most of this when it renders a field. Each input gets an id, such as id_title. Help text is written with the id id_location_helptext, and the error list with id_title_error. The input’s aria-describedby attribute lists those ids, so a screen reader reads the help and the error after the label, and aria-invalid="true" marks a field with an error. Figure 24.5 shows the pieces for the Time zone field, which has both help text and an error.
Figure 24.5 — The parts of one accessible field, and the attributes that connect them.
Otahque’s look needs Tailwind and daisyUI class names on those elements, and there is a catch: Chapter 14’s build reads class names only from the template folders named in source.css, so a class written in a Python file would never reach the stylesheet. Django lets the templates win instead. A form renderer decides which templates draw forms, and Django’s TemplatesSetting renderer looks for them through your TEMPLATES setting, so a project template with the same name as one of Django’s replaces it. Step 8 writes one template for every field, and two widget templates, for text-like inputs and for lists, that add daisyUI’s classes, and keeps Django’s ids and attributes.
Try it yourself
Que. 1 Sam’s form is posted with the title empty and status=published. Which of these does the response contain: a saved event, a published event, the message “This field is required.”, or the location he typed?
Flip to check your answerFold answer back
Answer. The message and the location. The empty title makes the form invalid, so nothing is saved, and the page is returned with every value Sam typed. status is not in the form’s fields, so it would be ignored even if the form were valid.
Prefer a Form, a ModelForm, or HTML by hand?
Use a ModelForm when the form creates or edits one model’s row: it takes the model’s fields and rules, and its fields list keeps the allowlist in one place. Use a plain Form when the values are not one row, such as a search box or a contact form. Avoid reading request.POST by hand in a view: every check, conversion, message, and redisplay is then yours to write and test, and it drifts from the model.
A form decides only what a person may type. Whether that person may open the page at all, and what they may see afterwards, are separate checks in the view and the model, and each needs its own test.
In practice: one event, two time zones
Situation. A community in Leeds runs a joint online session with a group in Bengaluru, and the organizer who types it lives in Leeds.
Application. The organizer chooses the zone the session is announced in, Asia/Kolkata, types the times as the announcement states them, and the page shows them in that zone. Nobody converts anything by hand.
Consideration. Attendees in Leeds still read Kolkata times on the event page until Chapter 28 shows each viewer their own time beside the event’s. Choosing the zone the audience will read is a product decision, not a technical one.
Start from Chapter 23, in the folder containing manage.py, with your own .env (including DJANGO_ADMIN_URL=admin/), the locked environment, 77 passing tests, every migration applied, the Node.js packages from Chapter 14 installed, and Sam’s superuser password from Chapter 18. Step 2 tries a first form in a practice file. Steps 3 and 4 write events/forms.py with its tests first. Step 5 adds the New event page: a view in events/views.py, an address in events/urls.py, the LOGIN_URL setting, the template events/templates/events/form.html, and a link in the navigation. Step 6 saves drafts, with one method added to events/models.py and messages in templates/base.html. Step 7 lets organizers and the administrator open a draft’s page. Step 8 renders the fields with Otahque’s styles, through config/renderers.py, a field template, two widget templates, static/otahque/source.css, and a small script. Step 9 proves the CSRF protection, writes the design note docs/design/event-draft-form.md, and commits. Every test goes in events/tests.py. At the end, 97 tests pass, Sam can save a draft for his New York clinic at 19:00 New York time, and there is no new migration.
The Custom Way
Without Django’s forms, every check, conversion, message, and redisplay is written by hand. This illustration checks two values the way a view would have to, and escapes a typed value before putting it back into the page. Run it with any Python, and do not add it to the project:
illustration_only/by_hand.py (not part of the project)
from html import escape
def check(data):
errors, cleaned = {}, {}
title = data.get('title', '').strip()
if title:
cleaned['title'] = title
else:
errors['title'] = 'This field is required.'
try:
cleaned['capacity'] = int(data.get('capacity', ''))
except ValueError:
errors['capacity'] = 'Enter a whole number.'
return errors, cleaned
for posted in ({'title': '', 'capacity': 'forty'},
{'title': 'Clinic', 'capacity': '50'}):
errors, cleaned = check(posted)
for name, value in (errors or cleaned).items():
print(f'{name}: {value}')
typed = 'Q&A "night"'
print(f'<input name="title" value="{escape(typed)}">')
Output
title: This field is required.
capacity: Enter a whole number.
title: Clinic
capacity: 50
<input name="title" value="Q&A "night"">
It handles two fields. Now count what is missing: there is no HTML for the inputs, no labels, no list of messages beside each field, no check that the request came from Otahque’s own page, and the rules are copies of the model’s, which will drift apart. escape() is there because a typed value written back into a page without it could close the attribute and add HTML of its own; forget it once and the page is open to attack. Django’s forms do each of these jobs, from the model, for every form.
The Django Way
Nine steps follow. Step 1 checks the start, Step 2 tries a plain form, Steps 3 and 4 build EventForm, Steps 5 to 7 build the page, its saving, and the draft’s page, Step 8 renders the fields, 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 77 test(s).
Creating test database for alias 'default'...
...
Ran 77 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 23’s:
Terminal
git status --short
git log --oneline -1
Output
... Configure the admin site
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: A first form, in a practice file
Before writing Otahque’s form, ask a small one the questions in Table 24.1. Create practice/first_form.py, in the practice folder beside your project that Chapter 16 created, holding:
../practice/first_form.py
import setup_django
from django import forms
class TitleForm(forms.Form):
title = forms.CharField(max_length=200)
capacity = forms.IntegerField(min_value=1)
empty = TitleForm()
print('empty:', empty.is_bound)
sent = TitleForm({'title': '', 'capacity': '40'})
print('sent:', sent.is_bound, sent.is_valid())
print(sent.errors.as_text())
print(repr(sent.data['capacity']), sent.cleaned_data)
fixed = TitleForm({'title': 'Clinic', 'capacity': '40'})
print(fixed.is_valid(), fixed.cleaned_data)
import setup_django is Chapter 16’s helper, which loads your project’s settings so the file can use Django. Run it from the folder that holds manage.py, in any of the four shells:
Terminal
uv run python ../practice/first_form.py
Output
empty: False
sent: True False
* title
* This field is required.
'40' {'capacity': 40}
True {'title': 'Clinic', 'capacity': 40}
The empty form is unbound. The sent form is bound and invalid, and errors.as_text() lists the message for title. sent.data['capacity'] is still the text '40', with quotes because repr() shows its type, while cleaned_data holds the number 40, and no title, because the title failed. The last form passes, and cleaned_data has both values, converted. That is all a form does: data in, checks, then either messages or clean values.
Step 3: EventForm, with its tests first
The first tests describe the form before it exists: status is not one of its fields and a posted value is ignored, a missing title is refused, a capacity of 0 is refused by Chapter 21’s model rule, and a zone outside the list is refused. Open events/tests.py and add one import after from . import views:
events/tests.py (after from . import views)
from .forms import EventForm
Then add at the end of the file:
events/tests.py (add at the end)
NEW_EVENT = {
'title': 'Online Django clinic',
'timezone': 'America/New_York',
'starts_at': '2026-12-03T19:00',
'ends_at': '2026-12-03T20:30',
'location': 'Online',
'capacity': '50',
}
def new_event_form(**changes):
"""Return an EventForm holding NEW_EVENT with changes."""
return EventForm(NEW_EVENT | changes)
class EventFormTests(TestCase):
"""EventForm's fields and the rules it reports."""
def test_status_is_not_a_field(self):
self.assertNotIn('status', EventForm().fields)
form = new_event_form(status='published')
self.assertTrue(form.is_valid(), form.errors)
self.assertEqual(form.save().status,
Event.Status.DRAFT)
def test_missing_title_is_refused(self):
form = new_event_form(title='')
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['title'],
['This field is required.'])
def test_zero_capacity_uses_the_model_rule(self):
form = new_event_form(capacity='0')
self.assertFalse(form.is_valid())
self.assertEqual(form.non_field_errors(),
['Capacity must be more than 0.'])
def test_unknown_zone_is_refused(self):
form = new_event_form(timezone='Mars/Olympus')
self.assertFalse(form.is_valid())
self.assertIn('timezone', form.errors)
NEW_EVENT holds what Sam’s browser will send for his clinic, as text, the way a browser sends it. new_event_form() builds a bound form from it with some values changed: | joins two dictionaries, and the right one’s values win. Run the new tests:
Terminal
uv run python manage.py test events.tests.EventFormTests
Output
Found 1 test(s).
...
ERROR: tests (unittest.loader._FailedTest.tests)
...
ImportError: Failed to import test module: tests
...
ModuleNotFoundError: No module named 'events.forms'
...
FAILED (errors=1)
The whole file fails to import, because events/forms.py does not exist yet, so Django reports the module rather than the four tests. Create events/forms.py:
events/forms.py
"""The events app's forms."""
from zoneinfo import available_timezones
from django import forms
from .models import Event
ZONE_CHOICES = [('', 'Choose a time zone')] + [
(name, name) for name in sorted(available_timezones())
]
def local_input():
"""Make a date-and-time box that the browser fills in."""
return forms.DateTimeInput(
attrs={'type': 'datetime-local'},
format='%Y-%m-%dT%H:%M',
)
class EventForm(forms.ModelForm):
"""Sam's new event. Status is not one of its fields."""
timezone = forms.ChoiceField(
choices=ZONE_CHOICES,
label='Time zone',
help_text='Starts and Ends are read in this zone.',
)
class Meta:
model = Event
fields = ['title', 'timezone', 'starts_at',
'ends_at', 'location', 'capacity']
labels = {'starts_at': 'Starts', 'ends_at': 'Ends'}
help_texts = {
'location': 'A venue address, or Online.',
}
widgets = {'starts_at': local_input(),
'ends_at': local_input()}
ZONE_CHOICES is the list for the Time zone field: an empty first choice that asks for a zone, then every zone name Python’s time-zone database knows, sorted. Each choice is a pair, the value sent and the text shown, and here they are the same. local_input() makes the widget for a date and time: type="datetime-local" asks the browser for its own date-and-time picker, and format writes a saved value back in the form that picker reads.
EventForm is a ModelForm. Meta.model names the model, fields is the allowlist, in the order the page shows them, labels and help_texts change what the page says, and widgets chooses the inputs. The field timezone is declared on the class itself, which replaces the one the model would give: the model has a text field for the zone, and the page needs a list. The model’s validator, validate_timezone_name(), still runs when the form calls the model’s validation. Run the tests again:
Terminal
uv run python manage.py test events.tests.EventFormTests
Output
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...
OK
Destroying test database for alias 'default'...
Common Error: fields = ’__all__’
With fields = '__all__', Django includes every editable field of the model, and test_status_is_not_a_field fails with AssertionError: 'status' unexpectedly found in {...}. Worse, a browser that sends status=published would publish the event. Name the fields; the test keeps the list honest when the model gains a field.
To see what the ModelForm built from the model, create practice/event_fields.py:
../practice/event_fields.py
import setup_django
from events.forms import EventForm
for name, field in EventForm().fields.items():
kind = type(field).__name__
print(f'{name:<10} {kind:<14} {field.required}')
Every field is required, because none of the model’s fields has blank=True, the setting that Chapter 20 said tells forms a field may be left empty. The model’s CharFields became form CharFields, its date and time fields DateTimeFields, and its PositiveIntegerField an IntegerField that refuses negative numbers. Only timezone is the one declared by hand.
Step 4: Read the times in the event’s zone
Sam’s form still reads every time in UTC. The tests say what it should do: his 19:00 in New York is midnight UTC on 4 December, the same text in Kolkata is 13:30 UTC, an end before the start is reported on the Ends field, and a time that New York’s clocks skip or repeat is refused with a message that says which. Add at the end of events/tests.py:
events/tests.py (add at the end)
def in_utc(form, name):
"""Return a cleaned time from form, shown in UTC."""
return form.cleaned_data[name].astimezone(UTC)
class EventZoneTests(TestCase):
"""Times are read in the event's own time zone."""
def test_times_are_read_in_the_event_zone(self):
form = new_event_form()
self.assertTrue(form.is_valid(), form.errors)
self.assertEqual(
in_utc(form, 'starts_at'),
datetime(2026, 12, 4, 0, 0, tzinfo=UTC),
)
def test_same_time_elsewhere_is_another_instant(self):
form = new_event_form(timezone='Asia/Kolkata')
self.assertTrue(form.is_valid(), form.errors)
self.assertEqual(
in_utc(form, 'starts_at'),
datetime(2026, 12, 3, 13, 30, tzinfo=UTC),
)
def test_end_before_start_is_shown_on_ends(self):
form = new_event_form(ends_at='2026-12-03T18:00')
self.assertFormError(
form, 'ends_at',
'An event must end after it starts.',
)
def test_skipped_time_is_refused(self):
form = new_event_form(
starts_at='2027-03-14T02:30',
ends_at='2027-03-14T04:00',
)
self.assertFormError(
form, 'starts_at',
'02:30 does not exist in America/New_York '
'that day: the clocks go forward.',
)
def test_repeated_time_is_refused(self):
form = new_event_form(
starts_at='2026-11-01T01:30',
ends_at='2026-11-01T03:00',
)
self.assertFormError(
form, 'starts_at',
'01:30 happens twice in America/New_York '
'that day: the clocks go back.',
)
assertFormError() checks that a form has exactly that message on that field. Run the tests:
Terminal
uv run python manage.py test events.tests.EventZoneTests
All five fail. The two times are five and a half hours apart in UTC only because they were both read as UTC. The end-before-start message exists, but it is Chapter 21’s constraint, which the model reports for the whole form rather than for Ends. And the two clock-change times were accepted, because UTC has no clock changes.
In events/forms.py, replace the import lines at the top, from from zoneinfo import available_timezones to from .models import Event, with:
events/forms.py (imports, replaced)
from datetime import UTC
from zoneinfo import ZoneInfo, available_timezones
from django import forms
from django.core.exceptions import ValidationError
from django.utils import timezone
from .models import Event
Add this function after local_input(), with two blank lines before and after it:
events/forms.py (after local_input)
def in_zone(value, zone_name):
"""Read a typed time as a time in the named zone."""
typed = timezone.make_naive(value)
zone = ZoneInfo(zone_name)
first = typed.replace(tzinfo=zone)
second = typed.replace(tzinfo=zone, fold=1)
if first.utcoffset() == second.utcoffset():
return first
params = {'time': typed.strftime('%H:%M'),
'zone': zone_name}
back = first.astimezone(UTC).astimezone(zone)
if back.replace(tzinfo=None) != typed:
raise ValidationError(
'%(time)s does not exist in %(zone)s that '
'day: the clocks go forward.',
code='skipped_time', params=params,
)
raise ValidationError(
'%(time)s happens twice in %(zone)s that day: '
'the clocks go back.',
code='repeated_time', params=params,
)
And add this method at the end of the file, inside EventForm, after the Meta class and one blank line below it:
events/forms.py (EventForm, add at the end)
def clean(self):
"""Read both times in the zone; end after start."""
data = super().clean()
zone = data.get('timezone')
for name in ('starts_at', 'ends_at'):
if zone and data.get(name):
try:
data[name] = in_zone(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.',
)
return data
clean() runs after every field has been cleaned, so data, the cleaned_data that super().clean() returns, holds every value that passed. For each time, in_zone() reads it again in the chosen zone. add_error() attaches a message to a field and removes that field from cleaned_data, which is why the comparison afterwards checks that both times are still there. When the end is not after the start, the message is attached to ends_at, and the model then skips its own constraint for that field, so the message appears once.
Under the Hood: how in_zone() finds a clock change
The field has already turned the text into an aware date and time in the current zone, UTC. timezone.make_naive() takes the zone off again, which gives back exactly what Sam typed, 19:00 on 3 December. replace(tzinfo=zone) then attaches the event’s zone. For an ordinary time that is the answer. Python marks the two readings of a repeated time with fold: 0 for the first, 1 for the second. For an ordinary time both give the same offset from UTC; for a time that happens twice, or not at all, they differ. To tell the two apart, the function converts the first reading to UTC and back: a time that does not exist comes back as a different time, an hour later, while a repeated one comes back unchanged.
Run the tests again:
Terminal
uv run python manage.py test events.tests.EventZoneTests
Output
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...
OK
Destroying test database for alias 'default'...
Then run all the event tests, to see that Step 3’s still pass:
Terminal
uv run python manage.py test events
Output
Found 53 test(s).
Creating test database for alias 'default'...
...
Ran 53 tests in ...
OK
Destroying test database for alias 'default'...
Step 5: The New event page, and who may open it
The page’s tests come first: a visitor is sent to sign in, a member without add_event is refused, and Sam sees a form with a label for every field, no status input, a CSRF token, and a link to the page in the navigation. Add one import to events/tests.py, after from django.contrib.auth import get_user_model:
events/tests.py (after the get_user_model import)
from django.contrib.auth.models import Permission
Then add at the end of the file:
events/tests.py (add at the end)
def member(email, *codenames):
"""Create a member holding the named permissions."""
name = email.split('@')[0].title()
user = User.objects.create_user(email, display_name=name)
user.user_permissions.add(*Permission.objects.filter(
codename__in=codenames
))
return user
class NewEventPageTests(TestCase):
"""Who may open the new-event page; what it saves."""
@classmethod
def setUpTestData(cls):
cls.sam = member('sam@example.org', 'add_event')
cls.sai = member('sai@example.org')
cls.url = reverse('events:create')
def test_visitor_is_sent_to_sign_in(self):
response = self.client.get(self.url)
sign_in = reverse('admin:login')
self.assertRedirects(
response, f'{sign_in}?next={self.url}',
fetch_redirect_response=False,
)
def test_member_without_permission_is_refused(self):
self.client.force_login(self.sai)
response = self.client.get(self.url)
self.assertEqual(response.status_code, 403)
def test_form_page_has_labelled_fields(self):
self.client.force_login(self.sam)
response = self.client.get(self.url)
self.assertTemplateUsed(response, 'events/form.html')
for name in ('title', 'timezone', 'starts_at',
'ends_at', 'location', 'capacity'):
self.assertContains(response, f'for="id_{name}"')
self.assertNotContains(response, 'name="status"')
self.assertContains(response, 'csrfmiddlewaretoken')
self.assertContains(response, f'href="{self.url}"')
member() creates a member and gives them the permissions named by their codenames, such as add_event, from the rows Chapter 18’s migrations created. reverse('admin:login') is the admin’s sign-in address, whatever your DJANGO_ADMIN_URL. fetch_redirect_response=False checks the redirect without following it. Run the tests:
Terminal
uv run python manage.py test events.tests.NewEventPageTests
Expected result, shortened with ...:
Output
Found 3 test(s).
...
ERROR: setUpClass (events.tests.NewEventPageTests)
...
django.urls.exceptions.NoReverseMatch: Reverse for ...
...
FAILED (errors=1)
...
reverse('events:create') fails in setUpTestData(), before any test runs, because no address has that name yet. Open events/urls.py and add a pattern before the event page’s:
events/urls.py (before the events/<int:event_id>/ pattern)
events/new/ comes before events/<int:event_id>/ only for readability; new is not a whole number, so the two never clash. In events/views.py, replace the import lines at the top, from from django.shortcuts import get_object_or_404, render to from .models import Event, with:
events/views.py (imports, replaced)
from django.contrib.auth.decorators import (
login_required, permission_required,
)
from django.shortcuts import get_object_or_404, render
from django.utils import timezone
from .forms import EventForm
from .models import Event
And add at the end of the file:
events/views.py (add at the end)
@login_required
@permission_required(
'events.add_event', raise_exception=True
)
def event_create(request):
"""Create an event, for members who may add events."""
form = EventForm()
return render(request, 'events/form.html',
{'form': form})
The decorators run before the view, from the top: login_required sends a visitor to sign in, and only then does permission_required check the permission, raising a 403 refusal with raise_exception=True. Without login_required, a visitor would also be refused with 403, instead of being offered a way to sign in. For now the view always shows an empty form; Step 6 handles what it sends.
Now tell Django where to send people to sign in. Open config/settings.py and add these lines after the ADMIN_URL check, the block that ends with 'with it; see .env.example.' and a closing bracket:
config/settings.py (after the ADMIN_URL check)
# Pages for signed-in people send everyone else here.
# Chapter 27 points it at the members' sign-in page.
LOGIN_URL = 'admin:login'
LOGIN_URL can be an address or, as here, a URL pattern’s name, which Django looks up when it needs it. Create events/templates/events/form.html:
events/templates/events/form.html
{% extends "base.html" %}
{% block title %}New event | Otahque{% endblock %}
{% block content %}
<h1>New event</h1>
<p>Otahque saves it as a draft. Only its organizers and
the administrator can see it until it is published.</p>
<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 draft</button>
</form>
{% endblock %}
{{ form }} draws every field with its label, help text, errors, and input, using Django’s own templates for now. {% csrf_token %} writes the hidden token. The button submits the form, which posts to the page’s own address, because the <form> element has no action. Last, replace templates/includes/site_nav.html with:
perms is a template variable that Django’s auth context processor provides: perms.events.add_event is true when the signed-in account holds that permission, so only people who may use the page see its link. Run the tests again:
Terminal
uv run python manage.py test events.tests.NewEventPageTests
Output
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...
OK
Destroying test database for alias 'default'...
Common Error: sent to /accounts/login/
Without the LOGIN_URL setting, test_visitor_is_sent_to_sign_in fails, saying Response redirected to '/accounts/login/?next=/events/new/', expected '/admin/login/?next=/events/new/', and in the browser the visitor lands on a “Page not found” page: /accounts/login/ is Django’s default address, and Otahque has no page there until Chapter 27.
Common Error: no {% csrf_token %}
Without the tag, test_form_page_has_labelled_fields fails with AssertionError: False is not true : Couldn't find 'csrfmiddlewaretoken' in the following response, and in the browser, pressing Save draft in Step 6 answers “Forbidden (403)” and “CSRF verification failed. Request aborted.” Put the tag inside every <form method="post">.
Start the development server, in any of the four shells, and leave it running:
Terminal
uv run python manage.py runserver
Open http://127.0.0.1:8000/events/new/ in a private browser window, so that you are not signed in. Django sends you to /admin/login/?next=/events/new/, the admin’s sign-in page. Sign in as sam@example.org with your Chapter 18 password, and you return to New event, with a New event link in the navigation. The page asks for a title, a time zone, starts, ends, a location, and a capacity, and the fields are not styled yet. Pressing Save draft shows the empty form again: the view does not read what it receives until Step 6.
Step 6: Save the draft, then redirect
The tests describe both outcomes of a POST. When the title is missing, the page returns with status 200, the message, and the values Sam typed, and nothing is saved. When everything holds, a draft is saved with Sam as its organizer, and the response redirects to the event’s page. Add these two methods at the end of events/tests.py, inside NewEventPageTests, after its last test and one blank line below it:
events/tests.py (NewEventPageTests, add at the end)
Both fail: the view ignores the POST, so the page has neither the message nor what was typed, and no event exists to fetch. First give Event a method that records an organizer. Open events/models.py and add, in the Event class after its __str__() method and one blank line below it:
events/models.py (Event, after __str__)
def add_organizer(self, member):
"""Make member a current organizer of this event."""
return self.organizer_assignments.create(
member=member
)
organizer_assignments is Chapter 20’s reverse relation from an event to its assignments, and create() on it saves a new assignment for this event. Keeping the action on the model follows Chapter 22’s rule: actions are model methods, and views stay thin. Now replace the import lines at the top of events/views.py, from the first line to from .models import Event, with:
events/views.py (imports, replaced)
from django.contrib import messages
from django.contrib.auth.decorators import (
login_required, permission_required,
)
from django.db import transaction
from django.shortcuts import (
get_object_or_404, redirect, render,
)
from django.utils import timezone
from .forms import EventForm
from .models import Event
And replace the event_create() function, from def event_create(request): to the end of the file, keeping its two decorator lines above it, with:
events/views.py (event_create, replaced)
def event_create(request):
"""Create an event, for members who may add events."""
if request.method == 'POST':
form = EventForm(request.POST)
if form.is_valid():
with transaction.atomic():
event = form.save()
event.add_organizer(request.user)
messages.success(request, 'Draft saved.')
return redirect('events:detail', event.pk)
else:
form = EventForm()
return render(request, 'events/form.html',
{'form': form})
On a POST, the form is bound to request.POST and checked. If it is valid, form.save() creates the event, a draft because status is not on the form, and add_organizer() records Sam. transaction.atomic(), from Chapter 21, makes the two writes one: if recording the organizer failed, the event would not be kept either, so there is never a draft that nobody organizes. messages.success() stores a message to show on the next page, and redirect() answers with status 302 and the event page’s address. If the form is invalid, the code falls through to render() with the same bound form, which still holds what Sam typed and the messages. The else: belongs to the first if: only a GET makes a new, empty form.
Messages need a place on every page. Open templates/base.html and add these lines inside <main>, before {% block content %}{% endblock %}, indented to match it:
templates/base.html (before the content block)
{% if messages %}
<div role="status">
{% for message in messages %}
<p class="alert alert-success">{{ message }}</p>
{% endfor %}
</div>
{% endif %}
messages is provided by the context processor Chapter 6’s settings already list. Showing a message removes it, so it appears once. role="status" asks screen readers to announce the message. Run the tests:
Terminal
uv run python manage.py test events.tests.NewEventPageTests
Output
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...
OK
Destroying test database for alias 'default'...
Common Error: an empty form after a mistake
If the view always makes a new form before render(), as in form = EventForm() just above it, test_invalid_post_keeps_values_saves_nothing fails with AssertionError: False is not true : Couldn't find 'This field is required.' in the following response. The page lost both the message and everything Sam typed. Pass the same bound form back to the template.
With the server running, reload New event, type the clinic, and press Save draft. Choose America/New_York in Time zone, 3 December 2026 at 19:00 for Starts, 20:30 for Ends, Online for Location, and 50 for Capacity. The browser follows the redirect to /events/6/, the next free number after Chapter 23’s events, and shows “Page not found”: the draft was saved, and the event page still shows published events only. Step 7 changes that. Try it again with Ends at 18:00, and the same page returns with “An event must end after it starts.” under Ends, and every value still in place.
Step 7: Let organizers and the administrator see a draft
The rule from Figure 24.4: a draft’s page is “not found” for visitors and members, and shown, with a note saying it is a draft, to its organizers and to accounts with view_event. The tests also follow Sam’s redirect to check that the page opens with “Draft saved.”. Add at the end of events/tests.py:
events/tests.py (add at the end)
class DraftPageTests(TestCase):
"""Who may see a draft, and the saved message."""
@classmethod
def setUpTestData(cls):
cls.sam = member('sam@example.org', 'add_event')
cls.sai = member('sai@example.org')
cls.admin = member('admin@example.org', 'view_event')
cls.draft = save_event(status=Event.Status.DRAFT)
cls.draft.add_organizer(cls.sam)
cls.url = reverse('events:detail',
args=[cls.draft.pk])
def test_draft_is_hidden_from_visitors_and_members(self):
response = self.client.get(self.url)
self.assertEqual(response.status_code, 404)
self.client.force_login(self.sai)
response = self.client.get(self.url)
self.assertEqual(response.status_code, 404)
def test_organizer_and_administrator_see_it(self):
for person in (self.sam, self.admin):
with self.subTest(person=person.email):
self.client.force_login(person)
response = self.client.get(self.url)
self.assertContains(
response, 'Draft: only its organizers'
)
def test_saved_draft_opens_with_message(self):
self.client.force_login(self.sam)
response = self.client.post(
reverse('events:create'), NEW_EVENT, follow=True
)
self.assertContains(response, 'Draft saved.')
self.assertContains(
response, '<h1>Online Django clinic</h1>',
html=True,
)
The administrator in these tests is any account with view_event; whether it is also staff makes no difference to Otahque’s own pages. follow=True makes the test client follow redirects, as a browser does. Run the tests:
Terminal
uv run python manage.py test events.tests.DraftPageTests
The first test passes already, because the event page has always hidden drafts. The other two fail with 404, and the second is counted twice, once for each person in its subTest(), which is why three failures are reported. Add a second method to Event, after add_organizer() and one blank line below it:
events/models.py (Event, after add_organizer)
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
if not user.is_authenticated:
return False
return self.organizer_assignments.filter(
member=user, revoked_at__isnull=True
).exists()
A published event is visible to everyone. Otherwise, has_perm() asks whether the account holds view_event; for a visitor, Django’s AnonymousUser holds no permissions, so the answer is false. A visitor cannot organize anything, so the method stops there. For a member, it looks for a current assignment, one with no revoked_at, and exists() asks the database only whether such a row exists. In events/views.py, add one import after from django.db import transaction:
events/views.py (after the transaction import)
from django.http import Http404
Then replace the event_detail() function with:
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(),
})
The view fetches the event whatever its status, then asks the model whether this person may see it, and raises Http404, Django’s “not found”, when not. The answer is the same as for an event that does not exist, so the page reveals nothing about drafts to people who may not see them. Last, open events/templates/events/detail.html and add these lines inside <article>, before <h1>{{ event.title }}</h1>:
events/templates/events/detail.html (before the h1)
{% if event.status != 'published' %}
<p class="rounded-box border border-base-content
px-3 py-1 text-sm">
{{ event.get_status_display }}: only its organizers
and the administrator can see this page.</p>
{% endif %}
get_status_display() is the readable label Chapter 16’s choices gave each status, such as “Draft”. The note uses text, not only a colour, to say what the page is. Run the tests, then every event test:
Terminal
uv run python manage.py test events.tests.DraftPageTests
Output
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...
OK
Destroying test database for alias 'default'...
Terminal
uv run python manage.py test events
Output
Found 61 test(s).
Creating test database for alias 'default'...
...
Ran 61 tests in ...
OK
Destroying test database for alias 'default'...
Chapter 19’s tests that hide drafts and cancelled events from visitors still pass, and so does Chapter 22’s test that the event page runs one query: a published event needs no permission or assignment check. Reload the “Page not found” address from Step 6. The clinic’s page now shows “Draft: only its organizers and the administrator can see this page.”, the title, and From and Until in New York time, with EST after each. Saving another event now ends on its page, under “Draft saved.”
Step 8: Render the fields with Otahque’s styles
The fields work, and they look like Django’s defaults. The tests describe the page Otahque wants: every field in a daisyUI fieldset, the five inputs and the list with daisyUI’s classes, the page loading the time-zone script, and, after a mistake, the error and help text still connected to their inputs. Add at the end of events/tests.py:
events/tests.py (add at the end)
class FormMarkupTests(TestCase):
"""Form fields use Otahque's templates and styles."""
@classmethod
def setUpTestData(cls):
cls.sam = member('sam@example.org', 'add_event')
cls.url = reverse('events:create')
def setUp(self):
self.client.force_login(self.sam)
def test_fields_use_otahque_styles_and_script(self):
response = self.client.get(self.url)
for text, count in (('class="fieldset"', 6),
('class="input w-full"', 5),
('class="select w-full"', 1)):
self.assertContains(response, text, count=count)
script = 'otahque/event-zone.js'
self.assertContains(response, script)
self.assertTrue(finders.find(script))
def test_errors_and_help_are_linked(self):
response = self.client.post(
self.url, NEW_EVENT | {'title': ''}
)
help_id = 'id_location_helptext'
for text in ('aria-invalid="true"',
'aria-describedby="id_title_error"',
'id="id_title_error"',
f'aria-describedby="{help_id}"',
f'id="{help_id}"'):
self.assertContains(response, text, count=1)
count= makes assertContains() check how many times the text appears. finders.find(), used by Chapter 14’s tests, checks that the static file exists. Run the tests:
Terminal
uv run python manage.py test events.tests.FormMarkupTests
Expected result, shortened with ...:
Output
Found 2 test(s).
...
.F
...
FAIL: test_fields_use_otahque_styles_and_script (...)
...
AssertionError: 0 != 6 : Found 0 instances of 'class="f...
...
FAILED (failures=1)
...
The first test fails on the first class it looks for. The second passes already: Django 6.1 writes the ids and the aria- attributes itself. It stays, because the templates you are about to write replace Django’s, and the test proves they keep those connections.
First, the renderer. Create config/renderers.py:
config/renderers.py
"""How Otahque draws its form fields."""
from django.forms.renderers import TemplatesSetting
class OtahqueFormRenderer(TemplatesSetting):
"""Use the project's own field and widget templates."""
field_template_name = 'forms/field.html'
TemplatesSetting finds form templates through the TEMPLATES setting, so a template in your templates/ folder replaces Django’s template of the same name, and field_template_name names the template that draws each field. In config/settings.py, add 'django.forms', to INSTALLED_APPS, after 'django.contrib.staticfiles',:
config/settings.py (INSTALLED_APPS, after staticfiles)
'django.forms',
That makes Django’s own form templates findable through TEMPLATES too, for every template you do not replace. Then add these lines after the TEMPLATES setting, before WSGI_APPLICATION:
config/settings.py (after TEMPLATES)
# Forms render with Otahque's field and widget templates,
# in templates/forms/ and templates/django/forms/widgets/.
FORM_RENDERER = 'config.renderers.OtahqueFormRenderer'
Now the templates. Create templates/forms/field.html, which draws one field:
field.id_for_label is the input’s id, field.auto_id is the same id that Django’s own field template uses to name the help text, and {{ field.errors }} draws the error list with its id. {{ field }} draws the input through its widget template. Create templates/django/forms/widgets/input.html, which replaces Django’s template for text, number, date-and-time, and other single inputs:
And templates/django/forms/widgets/select.html, for lists:
templates/django/forms/widgets/select.html
<select name="{{ widget.name }}" class="select w-full"
{% include "django/forms/widgets/attrs.html" %}>
{% spaceless %}
{% for group, choices, index in widget.optgroups %}
{% if group %}<optgroup label="{{ group }}">{% endif %}
{% for option in choices %}
{% include option.template_name with widget=option %}
{% endfor %}
{% if group %}</optgroup>{% endif %}
{% endfor %}
{% endspaceless %}
</select>
Both are Django’s own templates, with daisyUI’s classes added and laid out to read more easily. attrs.html is Django’s template that writes every other attribute, such as id, required, aria-invalid, and aria-describedby, so including it keeps them all. The names and folders must match Django’s exactly, django/forms/widgets/, or Django keeps using its own.
Next, the colours. Chapter 14’s theme has no colours for errors or success, so daisyUI’s success message would be grey and Otahque’s errors would be in the body’s colour. Open static/otahque/source.css and add these lines inside the otahque theme, after --color-neutral-content: #ffffff;:
static/otahque/source.css (in the theme, after --color-neutral-content)
/* daisyUI styles form fields inside the utilities layer,
so rules that change those fields sit there too. */
@layer utilities {
.fieldset :is(.input, .select) {
--input-color: #6b7686;
}
.fieldset [aria-invalid="true"] {
--input-color: var(--color-error);
}
.errorlist {
color: var(--color-error);
font-size: 0.875rem;
}
}
The colours were measured against the page’s white, as Chapter 13 measured the others: the error red has a contrast of 6.57 to 1 against white, white text on the success green 6.54 to 1, and the input border 4.60 to 1, against about 1.5 to 1 for daisyUI’s default. WCAG 2.2 asks for 4.5 to 1 for text and 3 to 1 for the edge of a control. The rules sit in @layer utilities because daisyUI 5 styles its fields in that layer, and a rule in an earlier layer would lose to it. A field with an error gets a red border and its message, so colour is never the only sign.
Last, the script. Create static/otahque/event-zone.js:
static/otahque/event-zone.js
// Choose the browser's time zone when none is chosen yet.
const field = document.getElementById('id_timezone');
const zone = Intl.DateTimeFormat()
.resolvedOptions().timeZone;
const known = field && [...field.options]
.some((option) => option.value === zone);
if (known && !field.value) {
field.value = zone;
}
Intl.DateTimeFormat().resolvedOptions().timeZone is the browser’s own zone name, such as Asia/Kolkata. The script chooses it only if it is in the list and nothing is chosen yet, so it never overrides a choice, and it leaves the field empty when it cannot help. Replace events/templates/events/form.html with:
events/templates/events/form.html
{% extends "base.html" %}
{% load static %}
{% block title %}New event | Otahque{% endblock %}
{% block content %}
<h1>New event</h1>
<p>Otahque saves it as a draft. Only its organizers and
the administrator can see it until it is published.</p>
<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 draft</button>
</form>
<script src="{% static 'otahque/event-zone.js' %}"
defer></script>
{% endblock %}
{% load static %} makes the static tag available, and defer runs the script after the page has loaded. Rebuild the stylesheet, so it holds the classes the new templates use, in any of the four shells:
Terminal
npm run build
Folder structure
> build
> npm run css -- -o static/otahque/site.css
...
/*! 🌼 daisyUI 5.7.50 */
Done in ...
The last line’s time varies. Run the tests again:
Terminal
uv run python manage.py test events.tests.FormMarkupTests
Output
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...
OK
Destroying test database for alias 'default'...
Common Error: TemplateDoesNotExist: django/forms/div.html
With the renderer set and 'django.forms' missing from INSTALLED_APPS, every page with a form fails with django.template.exceptions.TemplateDoesNotExist: django/forms/div.html. TemplatesSetting looks only where TEMPLATES looks, and Django’s own form templates are found there only through the django.forms app. Add it.
Common Error: help text without its id
If field.html writes the help text without id="{{ field.auto_id }}_helptext", the input still says aria-describedby="id_location_helptext", but nothing on the page has that id, and test_errors_and_help_are_linked fails with AssertionError: 0 != 1 : Found 0 instances of 'id="id_location_helptext"' (expected 1) in the following response. A screen reader then reads no help at all. Keep Django’s ids.
Reload New event in the browser. Each field now has a bold label, help text in grey under Time zone and Location, and a full-width box with a darker border, and Time zone already shows your browser’s zone. Clear Title and press Save draft: most browsers stop the form themselves and say the field must be filled in, because Django writes required on the input. That check is a convenience for people; the server’s check is the one that counts, because a script can post without a browser, and the tests post to the server directly. Type an Ends before Starts instead, and the page returns with the message in red under Ends, and a red border on the box.
Step 9: Prove the CSRF protection, record the design, and commit
The last test proves the protection Step 5’s tag relies on. Add one import to events/tests.py, changing from django.test import SimpleTestCase, TestCase to:
events/tests.py (the django.test import, replaced)
from django.test import Client, SimpleTestCase, TestCase
Then add at the end of the file:
events/tests.py (add at the end)
class CsrfTests(TestCase):
"""A post without the CSRF token is refused."""
@classmethod
def setUpTestData(cls):
cls.sam = member('sam@example.org', 'add_event')
cls.url = reverse('events:create')
def test_a_post_without_the_token_is_refused(self):
browser = Client(enforce_csrf_checks=True)
browser.force_login(self.sam)
refused = browser.post(self.url, NEW_EVENT)
self.assertEqual(refused.status_code, 403)
self.assertFalse(Event.objects.exists())
page = browser.get(self.url)
token = str(page.context['csrf_token'])
saved = browser.post(
self.url,
NEW_EVENT | {'csrfmiddlewaretoken': token},
)
self.assertEqual(saved.status_code, 302)
Client(enforce_csrf_checks=True) makes a test client that checks CSRF tokens, as a real request is checked. It posts without a token and is refused, nothing is saved, and then it fetches the page, takes the token the page was given, and posts again, successfully. page.context holds the variables the page’s template was given, including csrf_token. Run it:
Terminal
uv run python manage.py test events.tests.CsrfTests
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...
OK
Destroying test database for alias 'default'...
It passes the first time, because CsrfViewMiddleware has protected every POST since Chapter 6; until now nothing proved it. Every other POST test in this chapter uses the default client, which skips the check, and would pass with the middleware removed. This test would not.
Now record the design. Chapter 5 promised that low-level designs would begin when a feature needed one, and this form is the first. A low-level design, or LLD, describes how one feature works inside: its path through the code, its rules, and its failures. Create docs/design/event-draft-form.md:
docs/design/event-draft-form.md
# New event form: low-level design
Status: Drafted in Chapter 24, for review.
Who: members with events.add_event (Sam, on your
computer). 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.
## Validation layers
1. Fields: required values, lengths, whole numbers,
the zone from the list.
2. EventForm.clean(): starts and ends read in the
event's zone (in_zone); times a clock change skips
or repeats refused; ends after starts, on Ends.
3. Model full_clean(): validate_timezone_name and
Chapter 21's constraints (capacity more than 0).
4. 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.
- The edit form must show stored times in the event's
zone (Chapter 25); 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.
Run every test, then check that no model change needs a migration:
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'...
Terminal
uv run python manage.py makemigrations --check --dry-run
Output
No changes detected
The two methods added to Event are code, not fields, so the database is unchanged. Stage everything and check what is staged:
Terminal
git add config docs events static templates
git status --short
Output
A config/renderers.py
M config/settings.py
A docs/design/event-draft-form.md
A events/forms.py
M events/models.py
M events/templates/events/detail.html
A events/templates/events/form.html
M events/tests.py
M events/urls.py
M events/views.py
A static/otahque/event-zone.js
M static/otahque/site.css
M static/otahque/source.css
M templates/base.html
A templates/django/forms/widgets/input.html
A templates/django/forms/widgets/select.html
A templates/forms/field.html
M templates/includes/site_nav.html
Terminal
git commit -m "Add the new event form"
Table 24.2 — When something goes wrong
Symptom
Likely cause
Recovery
ModuleNotFoundError: No module named 'events.forms'
forms.py missing or misnamed
Create events/forms.py beside models.py
Visitor lands on Page not found at /accounts/login/
LOGIN_URL not set
Add it after the ADMIN_URL check (Step 5)
Forbidden (403) CSRF verification failed
{% csrf_token %} missing from the form
Add it inside the form element
Typed values vanish after a mistake
A new form is made before render()
Pass the bound form back (Step 6)
Saved event opens as Page not found
event_detail() not changed, or the account is not an organizer
Repeat Step 7; check the assignment in the admin
Times stored hours away
clean() missing, or zone chosen wrongly
Compare with Step 4; read the stored time in the admin
TemplateDoesNotExist: django/forms/div.html
'django.forms' missing from INSTALLED_APPS
Add it (Step 8)
Fields unstyled after Step 8
npm run build not run
Run it, then reload with the cache bypassed
When a file’s contents are in doubt, compare it with the listings here rather than deleting your work: git diff shows what changed since Chapter 23’s commit, and git stash can set your changes aside while you compare.
Work through Table 24.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 24.3 — Verification checklist for Chapter 24
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 and a desktop’s, with the browser set to the Kolkata zone for one and the New York zone for the other. Edge reported Kolkata’s zone by its older name, Asia/Calcutta, which is in the list too, so it was chosen.
Que. 2 What is the difference between form.data['capacity'] and form.cleaned_data['capacity'] for Sam’s clinic, and when can you read the second?
Flip to check your answerFold answer back
Answer. data holds the text the browser sent, '50'; cleaned_data holds the checked, converted value, the number 50. cleaned_data exists only after is_valid() has run, and holds only the values that passed.
Que. 3 Why does the view redirect after saving, instead of rendering the event’s page directly?
Flip to check your answerFold answer back
Answer. So the last request is a GET. Refreshing or going back after a redirect asks for the event’s page again; refreshing a page rendered by the POST would send the form again and save a second event.
Que. 4 Sam’s browser sends status=published with an otherwise valid event. What is saved, and which line of code decides that?
Flip to check your answerFold answer back
Answer. A draft. status is not in EventForm.Meta.fields, the allowlist, so the posted value is ignored and the model’s default, draft, is saved.
Que. 5 A capacity of 0 is refused, and the message appears at the top of the form rather than under Capacity. Which layer refused it, and why there?
Flip to check your answerFold answer back
Answer. The model, through full_clean(), which is_valid() calls for a ModelForm: the rule is Chapter 21’s constraint, and the model reports constraint messages for the whole form. The form’s field allows 0, because the model’s field is a PositiveIntegerField.
Que. 6 Every POST test in Steps 3 to 8 passes without a CSRF token. Why, and how does Step 9 prove the protection anyway?
Flip to check your answerFold answer back
Answer. Django’s test client skips the CSRF check by default. Step 9’s test creates its client with enforce_csrf_checks=True, so a POST without the token is refused with 403, and one with the page’s token is accepted.
Mini-Challenge
Que. 7 The community plans online calls at 01:30 on three days: in London on 28 March 2027 and on 31 October 2027, and in Kolkata on 28 March 2027. London’s clocks go forward at 01:00 on the first day and back at 02:00 on the second; Kolkata’s never change. Predict which of the three Sam’s form accepts, and why each refusal happens. Then check your prediction with a practice file that only validates, so nothing is saved.
Flip to check your answerFold answer back
Answer. London on 28 March is refused as a skipped time, because 01:00 to 01:59 does not exist that day. London on 31 October is refused as a repeated time, because 01:00 to 01:59 happens twice. Kolkata is accepted. One file that checks it, run with uv run python ../practice/challenge.py:
../practice/challenge.py
import setup_django
from events.forms import EventForm
BASE = {'title': 'Planning call', 'location': 'Online',
'capacity': '12'}
CASES = [('Europe/London', '2027-03-28'),
('Europe/London', '2027-10-31'),
('Asia/Kolkata', '2027-03-28')]
for zone, day in CASES:
form = EventForm(BASE | {
'timezone': zone,
'starts_at': f'{day}T01:30',
'ends_at': f'{day}T03:30',
})
errors = form.errors.as_data().get('starts_at')
result = errors[0].code if errors else 'accepted'
print(zone, day, result)
errors.as_data() gives the ValidationError objects behind the messages, and code is the short name in_zone() gave each one. The file calls no save(), so your rows are unchanged. The same typed text is fine in one zone and impossible in another, which is why the form reads it in the event’s zone.
What We Learned
A form sends values as text with POST; the view answers a GET with an empty form and a POST with errors or a redirect.
A Django form checks, converts, and explains; cleaned_data holds the values code may trust, only after is_valid().
A ModelForm takes its fields and rules from the model, and its fields list is an allowlist: what is not named cannot be set.
Rules live in four layers: fields, the form’s clean(), the model, and the database, and each rule lives as low as it can.
Typed times mean what the event’s zone says; times that a clock change skips or repeats are refused, not guessed.
login_required, permission_required, and a model method decide who may create events and who may see a draft.
Post/Redirect/Get and a message keep a refresh from saving twice and tell the person what happened.
CSRF tokens stop forged posts; only a test client with enforce_csrf_checks=True proves it.
A form renderer and templates put Otahque’s classes on fields while keeping labels, help, errors, and aria- attributes connected.
Key terms
Use Table 24.4 to explain this chapter’s ideas in your own words.
Table 24.4 — Key terms from Chapter 24
Term
Meaning
Form
Part of a page where people type values and send them; in Django, a class that checks them.
Field and widget
A field checks and converts one value; its widget writes the input's HTML.
Bound and unbound
A form given data, or an empty one for a GET.
cleaned_data
The checked, converted values, after is_valid().
ModelForm
A form whose fields and save() come from a model.
Allowlist
The fields a ModelForm may set: Meta.fields.
clean()
The form method for rules that compare fields.
Post/Redirect/Get
Answering a successful POST with a redirect, so the last request is a GET.
Message
A note stored for the next page, such as Draft saved.
login_required, permission_required
Decorators that ask for sign-in and a permission before a view runs.
CSRF
Cross-site request forgery: a request sent by another site in the person's name.
CSRF token
The secret a form must return, which another site cannot read.
Form renderer
The object that chooses the templates forms are drawn with.
aria-describedby
The attribute that points an input at its help text and errors.
Clock change
A local hour skipped or repeated when a zone's offset changes.
Low-level design (LLD)
How one feature works inside: path, rules, failures.
Readiness checkpoint: you are ready for Chapter 25 when all 97 tests pass, makemigrations --check --dry-run prints No changes detected, signing in as Sam and saving the New York clinic shows its draft page with “Draft saved.”, the draft’s address in a private window shows “Page not found”, and git status --short prints nothing. Chapter 25 edits a saved draft with the same form, and looks at its validation in depth. Return to the relevant step if any result is missing.
Git Commit
Your Chapter 24 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 config docs events static templates
git status --short
Output
A config/renderers.py
M config/settings.py
A docs/design/event-draft-form.md
A events/forms.py
M events/models.py
M events/templates/events/detail.html
A events/templates/events/form.html
M events/tests.py
M events/urls.py
M events/views.py
A static/otahque/event-zone.js
M static/otahque/site.css
M static/otahque/source.css
M templates/base.html
A templates/django/forms/widgets/input.html
A templates/django/forms/widgets/select.html
A templates/forms/field.html
M templates/includes/site_nav.html
Terminal
git commit -m "Add the new event form"
The commit holds the form, the page’s view, address, and template, two model methods, the messages block, the navigation link, the renderer and its three templates, the theme colours, the stylesheet, the time-zone script, twenty new tests, 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 25, 27, and 30. 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 is a Django form, and how do data and cleaned_data differ?
What the interviewer is testing: Do you know what a form does between the request and your code, and which values your code may trust?
Flip to check your answerFold answer back
Perfect answer: A Django form is a class that lists fields; each field knows how to check and convert one value and how to draw its input. I bind a form to what was sent, usually request.POST, and call is_valid(), which runs every field’s checks, the form’s clean(), and, for a ModelForm, the model’s validation. data is what the browser sent, always text; cleaned_data holds the converted values that passed, such as a number or a date and time, and exists only after is_valid(). My code reads cleaned_data, never request.POST. In Otahque, EventForm turns Sam’s text “2026-12-03T19:00” and “America/New_York” into an aware time, 19:00 in New York. When it is invalid, errors holds the messages, and I return the same bound form so the page shows them with what was typed.
Table 24.5 — A Form and a ModelForm compared
Aspect
Form
ModelForm
Fields from
The class
The model, chosen by Meta.fields
Rules
Fields and clean()
Those, plus the model's validation
Saving
Your code
save() creates or updates the row
Behind the scenes:
a form's checks (summary)
EventForm(request.POST) -> bound to the sent text
is_valid() -> fields, clean(), model rules
errors -> messages by field
cleaned_data -> values code may trust
Code proof: Sam’s clinic, before and after the checks:
../practice/l1_data.py
import setup_django
from events.forms import EventForm
form = EventForm({
'title': 'Online Django clinic',
'timezone': 'America/New_York',
'starts_at': '2026-12-03T19:00',
'ends_at': '2026-12-03T20:30',
'location': 'Online',
'capacity': '50',
})
print(form.is_bound, form.is_valid())
for name in ('capacity', 'starts_at'):
sent, clean = form.data[name], form.cleaned_data[name]
print(name, repr(sent), '->', clean)
The capacity arrives as the text '50' and leaves as the number 50; the start arrives as text and leaves as 19:00 with New York’s offset, five hours behind UTC.
Common mistakes:
Reading request.POST after is_valid(), and getting text instead of checked values.
Reading cleaned_data before calling is_valid().
Creating a new form after a failure, which loses the messages and what was typed.
Follow-up the interviewer might ask:
“Where would a rule about two fields go, and where would its message appear?”
“Why are values in request.POST always text?”
L2 (Mid-Level): Sam posts an end before the start, and adds status=published. Predict the response and what is saved.
What the interviewer is testing: Can you trace a bad POST through the form’s layers and the view, and say exactly what reaches the database?
Flip to check your answerFold answer back
Figure 24.6 — How a POST with two problems is answered.
Perfect answer: Nothing is saved, and Sam sees the same page again with status 200. The fields each pass on their own. status is not in the form’s fields, so the posted value is never read. The form’s clean() reads both times in New York’s zone and finds the end is not after the start, so it attaches “An event must end after it starts.” to Ends. Because the form has an error, the model then skips its own constraint for that field, so the message appears once. is_valid() returns false, the view never calls save() or add_organizer(), and it renders the same bound form, so every value Sam typed is still in its box. If he fixes the end, the event is saved as a draft, still not published, and the response is a redirect to its page.
Behind the scenes:
one invalid POST (summary)
status in POST -> not a field: ignored
clean() -> error on ends_at
model constraint -> skipped for ends_at
is_valid() False -> 200, same form, no save()
Code proof: the same data, checked without a view:
../practice/l2_predict.py
import setup_django
from events.forms import EventForm
from events.models import Event
before = Event.objects.count()
form = EventForm({
'title': 'Online Django clinic',
'timezone': 'America/New_York',
'starts_at': '2026-12-03T19:00',
'ends_at': '2026-12-03T18:00',
'location': 'Online',
'capacity': '50',
'status': 'published',
})
print(form.is_valid())
for name, messages in form.errors.items():
print(name, messages[0])
print('status' in form.fields)
print(Event.objects.count() == before)
Output
False
ends_at An event must end after it starts.
False
True
Invalid, one message on ends_at, no status field, and the number of events unchanged.
Common mistakes:
Expecting a 4xx status for a form error: the page is a normal response, with 200.
Thinking a hidden or removed input protects a field; only the allowlist does.
Saving first and validating after.
Follow-up the interviewer might ask:
“What would change if status were in fields?”
“Why does the model’s constraint not add a second message?”
L3 (Senior): Defend an explicit fields list over exclude or ’__all__’.
What the interviewer is testing: Do you understand mass assignment, and can you prove a form’s boundary with a test?
Flip to check your answerFold answer back
Figure 24.7 — Why the form names its fields.
Perfect answer: A ModelForm writes every field it holds from whatever the browser sends, and the browser is not under my control: anyone can add a value to a POST. With fields = '__all__', Otahque’s form would include status, and a crafted status=published would publish an event that was meant to be a draft. exclude is better only until someone adds a field to the model, such as an owner or a price, which then appears on the form unnoticed. An explicit list is an allowlist: a new field stays off the form until someone decides it belongs there. Django’s documentation recommends exactly that. I back it with a test that posts status=published and expects a draft, so a later change to the list fails the build rather than reaching production.
Behind the scenes:
a form's boundary (summary)
fields = [...] -> only these are set
'__all__' -> every editable field
exclude = [...] -> new fields slip in
crafted POST test -> the boundary holds
Code proof: the same POST through a form with every field and through EventForm, rolled back:
../practice/l3_allowlist.py
import setup_django
from django.db import transaction
from django.forms import modelform_factory
from events.forms import EventForm
from events.models import Event
SENT = {
'title': 'Allowlist check',
'timezone': 'America/New_York',
'starts_at': '2026-12-03T19:00',
'ends_at': '2026-12-03T20:30',
'location': 'Online',
'capacity': '50',
'status': 'published',
}
every_field = modelform_factory(Event, fields='__all__')
with transaction.atomic():
for label, form_class in (("'__all__'", every_field),
('EventForm', EventForm)):
event = form_class(SENT).save()
print(label, event.status)
transaction.set_rollback(True)
print(Event.objects.filter(title=SENT['title']).exists())
Output
'__all__' published
EventForm draft
False
The form with every field published the event; EventForm saved a draft; and the rollback left nothing behind.
Common mistakes:
Using '__all__' to save typing.
Removing an input from the template and thinking the field is protected.
Testing only what the form shows, not what a crafted POST can set.
Follow-up the interviewer might ask:
“How would you set a field the person must not choose, such as an owner?”
“Where else in Otahque could a crafted POST change more than it should?”
L4 (Staff): Organizers in New York report that their events appear five hours early. Diagnose and fix it.
What the interviewer is testing: Can you trace a time-zone bug from a report to its cause, prove it with a failing test, and fix it at the cause?
Flip to check your answerFold answer back
Figure 24.8 — Finding and fixing a time read in the wrong zone.
Perfect answer: Five hours is New York’s offset from UTC in winter, which points at the typed time being read in UTC. Django reads typed times in the current time zone, and Otahque’s is UTC, so 19:00 became 19:00 UTC, which New York shows as 14:00. I would confirm it with a test that posts 19:00 in New York and expects midnight UTC the next day; it fails with the five-hour difference. The fix belongs in the form: after the fields are cleaned, read each typed time again in the event’s own zone, which is what EventForm.clean() and in_zone() do. Activating the organizer’s zone would be wrong, because the event’s zone, not the organizer’s, gives the time its meaning. Then I would refuse the times a clock change skips or repeats, fix the stored rows that were saved wrongly, after checking which events were affected, and keep the test.
Behind the scenes:
a time read twice (summary)
field clean -> 19:00 in UTC
make_naive() -> back to 19:00, no zone
replace(tzinfo) -> 19:00 in the event's zone
fold 0 and 1 -> differ: refuse the time
Code proof: a ModelForm that reads the time in UTC beside EventForm:
../practice/l4_zone.py
import setup_django
from datetime import UTC
from django.forms import modelform_factory
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',
}
plain = modelform_factory(Event, fields=list(SENT))
starts = []
for label, form_class in (('as UTC', plain),
('in its zone', EventForm)):
form = form_class(SENT)
form.is_valid()
starts.append(form.cleaned_data['starts_at'])
print(label, starts[-1].astimezone(UTC))
print(starts[1] - starts[0])
Output
as UTC 2026-12-03 19:00:00+00:00
in its zone 2026-12-04 00:00:00+00:00
5:00:00
The same text, two instants, exactly five hours apart: the bug, reproduced, beside the fix.
Common mistakes:
Setting TIME_ZONE to New York, which breaks every event elsewhere.
Shifting the stored times by five hours, which is wrong in summer.
Fixing the rows but not the form, so the next event is wrong too.
Follow-up the interviewer might ask:
“When Chapter 28 activates each viewer’s zone, what changes for this form?”
“How would you find the events that were saved wrongly?”
L5 (Lead): A manager wants anyone, without an account, to be able to submit event ideas. What do you advise?
What the interviewer is testing: Can you weigh a product request against access rules and abuse, and keep the boundary decided rather than accidental?
Flip to check your answerFold answer back
Figure 24.9 — Why ideas from visitors need their own design.
Perfect answer: I would start from the goal, more good event ideas, and from Otahque’s boundary: creating an event needs an account with add_event, and visitors only read published events. Letting anonymous visitors create Event rows, even drafts, would invite spam and abuse, fill organizers’ lists with rows nobody owns, and need limits Otahque does not have yet. If the community wants ideas, I would propose a separate design: a proposal record, not an event, submitted after sign-in, which Chapter 27 provides, with rate limits, reviewed by organizers who can turn a good one into a draft. That is a scope change to Chapter 2’s requirements, so it is the community’s decision, recorded with its abuse cases and tests. Until then, the current tests prove the boundary: a visitor is sent to sign in, and a member without the permission is refused.
Behind the scenes:
ideas from visitors (summary)
Event rows -> organizers with add_event
anonymous POST -> spam, no owner, no limits
proposal record -> sign-in, limits, review
scope change -> decided, then tested
Code proof: the New event view, asked by a visitor and by Sai:
../practice/l5_access.py
import setup_django
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import PermissionDenied
from django.test import RequestFactory
from accounts.models import User
from events.views import event_create
factory = RequestFactory(HTTP_HOST='localhost')
sai = User.objects.get(email='sai@example.org')
for person in (AnonymousUser(), sai):
request = factory.get('/events/new/')
request.user = person
try:
response = event_create(request)
print(person, response.status_code,
response['Location'])
except PermissionDenied:
print(person, 'refused: 403')
RequestFactory builds a request without the server, and HTTP_HOST='localhost' gives it an address your settings allow. The visitor is sent to sign in, and Sai, who holds no permission, is refused.
Common mistakes:
Opening the event form to visitors because the form already validates.
Treating a product question, who may propose, as a technical one.
Adding a public form without rate limits or review.
Follow-up the interviewer might ask:
“Which abuse cases would you write tests for first?”
“How would Chapter 30’s roles change who may create events?”
Next: Chapter 25 edits Sam’s saved draft with the same form, and follows its validation, from the fields to the model, in depth.