ContentsClose contents
Pre-release
Chapter 26 · Publishing, cancelling, and deleting an event: Sam takes the clinic publicCHAPTER 26

Complete six-part pre-release for review. Roles, groups, and audit records are Chapter 30; registration and its window are Chapter 31; telling members of a cancellation waits for email in Chapters 43 and 44. One 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-SIX

Publishing, cancelling, and deleting an event: Sam takes the clinic public

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

Prerequisites: Chapters 15 to 25, including the Chapter 25 project, its 124 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: A description on every event; the event’s own address in one place; a My events page for organizers; a Publish button that refuses a draft until nothing is missing and says what is; Cancel and Delete for the right states and the right people, each behind a POST; a copy action for the next week’s clinic; one migration; and a written design of the event’s states

Why This Matters

Sam’s Online Django clinic is saved, edited, and still a draft that only he and the administrator can see. The group in New York cannot register for a draft, and Sam cannot find it again without remembering its address. He needs four things, and each one has a trap.

First, he needs to find his own events. Chapter 23 promised organizers “a few focused screens”, and today Sam reaches his draft only by typing /events/6/. Second, he needs to publish it. Publishing is the moment a draft becomes public, so it should happen only when nothing is missing, and the clinic has no description yet, which Chapter 2’s criteria require. Third, plans change: a published event may have to be cancelled, and a draft he no longer wants should be deleted. Fourth, the clinic is weekly, and typing it again each Thursday is a chore.

The traps are real. A Delete link that works when you click it also works when a search crawler follows it. A Publish button that checks nothing sends half-written events to the public. A Delete that works on a published event throws away the registrations of the members who planned to attend. And a Cancel that quietly hides the event leaves Sai, who holds a place, with a “not found” page.

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

  • describe an event’s life as three states and a short list of allowed moves, and say who may make each move and when it is refused;
  • explain why a change of state travels in a POST and never in a GET, and prove that a link, a prefetch, and a wrong method change nothing;
  • add a field to an existing table with one migration, read the SQL it will run, and roll it back;
  • put “is this event ready?” in the model, so that every page and the shell agree, and tell the person each missing detail;
  • delete a draft with its organizer assignments in one transaction, and explain why Django refused to delete it before;
  • let an event say where it lives with get_absolute_url(), and build a page that lists only the events a person organizes, with a query count that does not grow.

Roles, groups, and a record of who did what are Chapter 30. The sign-in page members see is Chapter 27, and each viewer’s own time zone is Chapter 28. Registration, with its window, is Chapter 31. Locking a row against two people acting at once is Chapter 33, and telling members that an event was cancelled waits for email in Chapters 43 and 44. The cover image of an event, which a copy will carry, is Chapter 42.

PAGE 001

What You Need to Know

An event’s life: states and moves

Chapter 16 gave Event a status with three values: draft, published, and cancelled. Until now the only way to change it was the admin site. This chapter makes the moves explicit.

New Concept: a state machine

What problem exists? A status column can hold any of its values at any time. Nothing says that a cancelled event may not become a draft again, or that a draft may not be cancelled.

What did people do before? They wrote if event.status == 'draft' in whichever view needed it, and each view invented its own rule.

What is it? A state machine is a short list of states and the moves allowed between them, each move with a rule about who may make it and when it is refused. Anything not on the list is refused.

Why use it? The list is small enough to draw, test, and defend. A new rule is a change to one place.

Now let’s use it. Step 2 draws Otahque’s three states, and Steps 6 to 9 give each move one method on the model.

The states and the moves this chapter allows are drawn in Figure 26.1.

Three state boxes in a row joined by arrows. Draft, in grey, is seen only by organizers and view_event holders with a Draft banner. An arrow labelled publish leads to Published, in green, seen by everyone and in the lists. An arrow labelled cancel leads to Cancelled, in red, seen by anyone with the address under a tag and in no list. A second arrow from Draft leads to an orange box: delete, a draft with no registrations is removed. A grey box says there is no unpublish and cancelled is final, so a cancelled event is run again by copying it to a new draft. A blue box above says each move is a POST allowed only for a current organizer who holds change_event.
Figure 26.1 — The event’s three states and the moves between them.

Table 26.1 lists each move with where it starts, where it ends, and when it is refused. The last row is not a move between states: copying makes a new draft and leaves the original alone.

Table 26.1 — The moves an event may make
Move From To Refused when
publish draft published not a draft; no description; the start is not in the future; no current organizer
cancel published cancelled not published
delete draft gone not a draft; any registration exists
copy any state a new draft the new start is missing or unreadable

Two choices in the table are decisions, not facts about Django. There is no unpublish: a published event may already have registrations, and hiding it would leave those members without a page. And cancelled is final: to run a cancelled event again, you copy it, which creates a fresh draft with none of the old registrations. These choices are Chapter 26’s design, recorded in docs/design/event-states.md in Step 10, and you can revisit them when members’ needs are clearer.

Ready is not the same as valid

Chapter 21 and Chapter 25 made sure that every saved event is valid: it ends after it starts, its capacity is above zero and never below the places taken. A draft, though, may be valid and still unfinished. Sam saved the clinic without a description, and that is allowed.

Readiness is a stricter test, applied only at the move from draft to published. Chapter 2’s publishing criteria name a description, a start in the future, and an assigned organizer. The registration window is the fourth criterion, and it waits for Chapter 31, which defines it. So this chapter’s rule has three conditions, and each missing one gets its own message.

New Concept: readiness, kept in the model

What problem exists? Where should “is this event ready to publish?” live? If it lives in the view, the shell and the admin cannot ask it. If it lives in the template, hiding a button looks like a check but a hand-made request still gets through.

What did people do before? They hid the Publish button when something was missing, and checked nothing on the server.

What is it? A model method, readiness_problems(), returns the list of what is missing, and publish() refuses when the list is not empty. The page only shows the result.

Why use it? One question, one answer, in one place, asked the same way by every caller.

Now let’s use it. Step 6 writes both methods before any view uses them.

A description, and a migration

Readiness needs a description to check, so the first job is to add one. Event.description is a TextField(blank=True): a draft may leave it empty, and readiness demands it later. Django’s convention, stated in its documentation for string-based fields, is to use an empty string, not NULL, as the “no data” state, so the field has blank=True and no null=True.

Adding a field to a table that already has rows is the first schema change since Chapter 21. Django’s migration for it is generated from the model and then applied. Two commands let you see what will happen before it does, and one lets you undo it:

  • sqlmigrate events 0004 prints the SQL for a migration without running it, and --backwards prints the SQL that would unapply it;
  • migrate --plan lists what a migrate command would do;
  • migrate events 0003 moves the events app back to its third migration, which unapplies the fourth.

Step 3 runs all of them on the real project. The SQL depends on the database: on SQLite, Django rebuilds the table, while other databases add a column in one statement, so read the output on your own machine.

Under the Hood: what unapplying a migration does

Unapplying 0004 runs the SQL that sqlmigrate --backwards prints. For a new column, that SQL drops the column, so the descriptions you typed are gone with it. Unapplying is therefore safe on your own machine and a serious step on a database holding real data. Django’s documentation says a migration containing an irreversible operation cannot be reversed at all. On a shared or deployed database, the usual route is a new migration that moves forward, not a rollback.

A link and a form are not the same thing

A web browser sends a GET request when you follow a link or type an address, and a POST request when you submit a form. HTTP, the protocol under every web page, calls GET and three other methods safe: RFC 9110, section 9.2.1, says a safe method’s semantics are essentially read-only, and that this lets automated processes, such as search crawlers, and browsers that prefetch a page, use it freely. A client that follows every link on a page is not misbehaving. A page that changes data when it is followed is.

So Otahque’s rule is plain: a GET only reads. Anything that changes data, publishing, cancelling, deleting, or copying, is a POST, sent by a form with Chapter 24’s CSRF token. A view that accepts only POST answers a GET with 405 Method Not Allowed. The standard requires a 405 response to carry an Allow header listing the methods the resource does support, and Django’s decorator sets it, as Step 6’s test shows.

Two boxes side by side and two banners below. A red box titled A link: GET says a crawler, a prefetch, or a click on a shared address sends a GET, and if the view deleted on a GET, each of them would delete. A green box titled A form: POST says only a form with the CSRF token sends the POST the view accepts, and a GET to a POST-only view answers 405. A grey banner says safe methods only read and a change of state travels in a POST, and only for someone who may make it. An orange banner says deleting adds one step: a GET shows a confirmation page, and only its POST deletes.
Figure 26.2 — Why a link may never change anything, and what a form adds.

Deleting adds one step. A delete cannot be undone, so Otahque shows a confirmation page on GET, which only reads, and deletes on the POST that page’s button sends. Publishing and cancelling have no confirmation page: publishing is checked by readiness and is reversible only by cancelling, and cancelling says plainly beside its button that it cannot be undone. You can change that choice if your community wants a confirmation page there too.

Why Django refused to delete Sam’s draft

Chapter 20 made OrganizerAssignment.event a ForeignKey with on_delete=PROTECT. That setting forbids deleting an event while an assignment points at it: Django raises ProtectedError, which Django’s documentation describes as a subclass of IntegrityError. The protection is deliberate, because an assignment is part of who ran an event. It also means that deleting Sam’s own draft fails today. Step 2 shows the message.

For a draft with no registrations, the right order is clear: delete the draft’s assignments, then the draft, and do both in one transaction, so that either both happen or neither does. A draft that someone registered for is another matter, and Otahque refuses to delete it.

Who may do what

Chapter 25 decided who may edit an event: someone who holds events.change_event and is a current organizer of that event, written once in Event.can_be_edited_by(). This chapter’s actions use the same rule. Chapter 30 will design roles and groups properly, and the one method is where it will plug in, so no view tests roles on its own.

The access check has two outcomes, as in Chapter 25. A person who may not see the event gets 404, so a draft’s existence stays private. A person who may see it but not change it gets 403. A visitor who is not signed in is sent to sign in. The answers for the three actions are in Figure 26.3.

A grid with three action columns, Publish a draft, Cancel a published event, and Delete a draft, and three person rows. A visitor who is not signed in is sent to sign in for all three, in grey. Sai, a member, gets not found 404 for publish, refused 403 for cancel, and not found 404 for delete, in red. Sam, an organizer, gets published or the missing details named, cancelled, and deleted if no registrations, in green. A note says Sai may see a published event, so her refusal is 403, and she may not see a draft, so for her it is 404.
Figure 26.3 — Who may do what, for each of the three actions.

The cancelled event, as members see it

Chapter 24 hid cancelled events from everyone but organizers, as it hid drafts. That is wrong for a cancelled event, because members who hold places need to learn that the event is off. This chapter changes the rule: a cancelled event’s page is shown to everyone who has its address, under a Cancelled tag, with no line about places left. It stays out of the upcoming and past lists, and the registrations are untouched. Organizers still see it, tagged, on their own My events page.

Two earlier choices change with it, and you will see both in Step 7: Event.is_visible_to() now hides only drafts, and one Chapter 24 test, which expected a 404 for a cancelled event, changes in place.

Try it yourself

Que. 1 Table 26.1 has no “unpublish” row. A member asks the organizer to hide a published event “just for a day”. What can Sam do with this chapter’s moves, and what would he lose by cancelling?

Flip to check your answerFold answer back

Answer. Nothing in this chapter hides a published event. Sam can cancel it, which shows a Cancelled tag to everyone and keeps every registration, or leave it published. Cancelling is final, so he would run the event again by copying it to a new draft and publishing that, and the members’ old registrations would not carry over.

Que. 2 A search crawler opens every link on Sam’s My events page. Which of the page’s links could change data if the views were written carelessly, and which are safe because of this chapter’s rules?

Flip to check your answerFold answer back

Answer. A Delete link would be the dangerous one, and so would any Publish or Cancel link. Edit and Copy open pages with forms, so following them changes nothing. Otahque’s Delete link opens a confirmation page, and publishing and cancelling are buttons in forms, so a crawler sees only GET pages that read.

PAGE 002

How We Build It

Start from Chapter 25, in the folder containing manage.py, with your own .env, the locked environment, 124 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, with Sam as its organizer. The new files are events/templates/events/manage.html, delete.html, copy.html, templates/django/forms/widgets/textarea.html, events/migrations/0004_event_description.py, and docs/design/event-states.md. The commands below are written the same for Windows PowerShell, Git Bash, macOS, Linux, and WSL shells; the chapter’s checks ran in the first two. Each step writes its tests first and runs them to see them fail, then writes the code.

One date matters. The clinic starts on 3 December 2026. Publishing refuses an event whose start is not in the future, so if your clock is already past that day, Step 6 will refuse the clinic with exactly the message the chapter teaches. Edit the clinic’s dates with the Chapter 25 page before you publish it.

The Custom Way

Without the rules of this chapter, an event’s views delete when their address is opened. This illustration, plain Python with no Django, shows what a crawler does to each style. Run it with any Python, and do not add it to the project:

START = {6: 'Online Django clinic', 7: 'Python meetup'}
LINKS = ['/events/6/delete/', '/events/7/delete/']


def by_link(events, path, method):
    """Delete whenever the address is opened."""
    events.pop(int(path.split('/')[2]), None)


def by_form(events, path, method):
    """Delete only for a POST; refuse anything else."""
    if method != 'POST':
        return 405
    events.pop(int(path.split('/')[2]), None)


def crawl(handler):
    """Act as a crawler: open every link with a GET."""
    events = dict(START)
    for link in LINKS:
        handler(events, link, 'GET')
    return events


print('by link:', crawl(by_link))
print('by form:', crawl(by_form))
by link: {}
by form: {6: 'Online Django clinic', 7: 'Python meetup'}

A crawler opens every address it finds with a GET. The first handler treats the address itself as the instruction, so the crawl emptied the list. The second accepts only a POST, so the same crawl changed nothing. The rest of the chapter builds the second kind, for an event’s whole life.

The Django Way

Django gives each piece a place. The model holds the rules: what is missing, which moves are allowed, and the deletion in one transaction. A decorator, require_POST, answers anything but a POST with 405. A shared function decides who may act. Templates show buttons only to the people who may use them, and the views still refuse everyone else.

Step 1: Check the starting point

Run every test, beside manage.py:

uv run python manage.py test

Expected result, shortened with ...:

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

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

Then confirm that nothing is waiting to be committed and that the last commit is Chapter 25’s:

git status --short
git log --oneline -1
... Add the Edit event page

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: The states on paper, and why Sam’s draft will not delete

Table 26.1 and Figure 26.1 are the plan for Steps 6 to 9, so Step 2 only proves what the plan has to deal with. Sam’s draft has an organizer assignment, and the assignment protects it. This practice file tries to delete the clinic and prints what Django says. It runs inside Django’s shell against your own database, and it changes nothing, because the delete fails before it removes anything:

from textwrap import fill

from events.models import Event

draft = Event.objects.get(pk=6)
try:
    draft.delete()
except Exception as error:
    print(type(error).__name__)
    print(fill(error.args[0], 60))
uv run python manage.py shell -c "exec(open('probe.py').read())"
15 objects imported automatically (use -v 2 for details).

ProtectedError
Cannot delete some instances of model 'Event' because they
are referenced through protected foreign keys:
'OrganizerAssignment.event'.

That is ProtectedError, the exception Django raises for a protected foreign key. It names the model that holds the protection, OrganizerAssignment.event. Delete probe.py now. Step 8 will delete the assignments first, and only then the event.

Step 3: A description, and the migration for it

Chapter 2’s criteria need a description, so the field comes first. Tests first: a draft saves without one, the field sits right after Title, and the event page keeps the line breaks the organizer typed. Add this at the end of events/tests.py:

class DescriptionTests(TestCase):
    """Descriptions: optional for drafts, shown on pages."""

    def test_a_draft_saves_without_one(self):
        form = new_event_form()
        self.assertTrue(form.is_valid(), form.errors)
        self.assertEqual(form.save().description, '')

    def test_it_follows_the_title_and_is_saved(self):
        names = list(EventForm().fields)
        self.assertEqual(names[:2], ['title', 'description'])
        form = new_event_form(description='For beginners.')
        saved = form.save()
        self.assertEqual(saved.description, 'For beginners.')

    def test_the_page_keeps_line_breaks(self):
        event = save_event(description='One.\nTwo & three.')
        url = reverse('events:detail', args=[event.pk])
        response = self.client.get(url)
        self.assertContains(
            response, 'One.<br>Two &amp; three.'
        )

One existing test changes in place, because the form has a new field and a new kind of box. In FormMarkupTests.test_fields_use_otahque_styles_and_script, replace the three counted classes with these four, since the form now has seven fieldsets and one textarea:

        for text, count in (('class="fieldset"', 7),
                            ('class="input w-full"', 5),
                            ('class="textarea w-full"', 1),
                            ('class="select w-full"', 1)):

Run the two classes and watch them fail:

uv run python manage.py test events -k Description -k FormMarkup
Found 5 test(s).
Creating test database for alias 'default'...
...
AttributeError: 'Event' object has no attribute 'description'
TypeError: Event() got unexpected keyword arguments:
    'description'
AssertionError: Lists differ: ['title', 'timezone'] !=
    ['title', 'description']
Ran 5 tests in ...s

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

Add the field to the model. In events/models.py, replace the title and starts_at lines of Event with these three:

    title = models.CharField(max_length=200)
    description = models.TextField(blank=True)
    starts_at = models.DateTimeField()

blank=True lets forms accept an empty value, and there is no null=True: the “no data” value is the empty string, which is Django’s convention for text fields. In events/forms.py, replace the form’s Meta class so that the field follows the title, has a five-row box, and explains itself:

    class Meta:
        model = Event
        fields = ['title', 'description', 'timezone',
                  'starts_at', 'ends_at', 'location',
                  'capacity']
        labels = {'starts_at': 'Starts', 'ends_at': 'Ends'}
        help_texts = {
            'description': 'Needed before the event can be '
                           'published.',
            'location': 'A venue address, or Online.',
        }
        widgets = {
            'description': forms.Textarea(attrs={'rows': 5}),
            'starts_at': local_input(),
            'ends_at': local_input(),
        }

Django draws a Textarea with its own template, so Chapter 24’s styling needs one more widget template. Create templates/django/forms/widgets/textarea.html:

<textarea name="{{ widget.name }}" class="textarea w-full"
          {% include "django/forms/widgets/attrs.html" %}>
{% if widget.value %}{{ widget.value }}{% endif %}</textarea>

Show the description on the event page: in events/templates/events/detail.html, replace the title line with these four lines. linebreaksbr keeps the line breaks as <br> and, like every template variable, escapes any HTML:

    <h1>{{ event.title }}</h1>
    {% if event.description %}
      <p>{{ event.description|linebreaksbr }}</p>
    {% endif %}

And let the admin show it: in events/admin.py, replace the first line of EventAdmin.fields so that it reads:

    fields = ['title', 'description', 'status',
              'starts_at', 'ends_at',

Now generate the migration, and read it before you apply it:

uv run python manage.py makemigrations -n event_description
Migrations for 'events':
  events\migrations\0004_event_description.py
    + Add field description to event
from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('events', '0003_rules'),
    ]

    operations = [
        migrations.AddField(
            model_name='event',
            name='description',
            field=models.TextField(blank=True),
        ),
    ]

The migration adds one field. To see the SQL it will run, without running it, use sqlmigrate with the app and the migration’s number:

uv run python manage.py sqlmigrate events 0004
BEGIN;
--
-- Add field description to event
--
CREATE TABLE "new__events_event" ("id" integer NOT NULL
    PRIMARY KEY AUTOINCREMENT, "description" text NOT NULL,
    "title" varchar(200) NOT NULL, "starts_at" datetime NOT
    NULL, "ends_at" datetime NOT NULL, "timezone" varchar(64)
    NOT NULL, "location" varchar(200) NOT NULL, "capacity"
    integer unsigned NOT NULL CHECK ("capacity" >= 0),
    "status" varchar(20) NOT NULL, CONSTRAINT
    "event_capacity_gt_0" CHECK ("capacity" > 0), CONSTRAINT
    "event_ends_after_start" CHECK ("ends_at" >
    ("starts_at")), CONSTRAINT "event_status_valid" CHECK
    ("status" IN ('draft', 'published', 'cancelled')));
INSERT INTO "new__events_event" ("id", "title", "starts_at",
    "ends_at", "timezone", "location", "capacity", "status",
    "description") SELECT "id", "title", "starts_at",
    "ends_at", "timezone", "location", "capacity", "status",
    '' FROM "events_event";
DROP TABLE "events_event";
ALTER TABLE "new__events_event" RENAME TO "events_event";
COMMIT;

On SQLite, Django builds a new table with the new column, copies every row across with an empty string for the new column, and renames it. Other databases do this with one ALTER TABLE ... ADD COLUMN statement, so run the command on your own database before you trust a prediction. The existing rows get '' and your clinic stays valid. Now the other direction:

uv run python manage.py sqlmigrate events 0004 --backwards
BEGIN;
--
-- Add field description to event
--
ALTER TABLE "events_event" DROP COLUMN "description";
COMMIT;

That is what unapplying does: it drops the column, and the descriptions typed into it. Apply the migration:

uv run python manage.py migrate
Operations to perform:
  Apply all migrations: accounts, admin, auth, contenttypes,
    events, registrations, sessions
Running migrations:
  Applying events.0004_event_description... OK

Run the two classes again:

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

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

Rebuild the stylesheet, because the new template class textarea has to be in it:

npm run build

Common Error: a field with no default and no blank

Without blank=True on the field, a new required column has no value for the rows that already exist, and Django cannot decide one for you: makemigrations stops and asks for a one-off default, or, with no way to ask, refuses. Add blank=True, or give a default, and run makemigrations again. Do not edit the numbered migration to make the question go away.

Last, rolling back. Imagine the migration was applied and you want it gone. This is safe on your own machine and never on a database whose rows matter, because it drops the column. Check where you are, look at the plan, go back to the third migration, and check again:

uv run python manage.py showmigrations events
uv run python manage.py migrate events 0003
uv run python manage.py showmigrations events
Operations to perform:
  Target specific migration: 0003_rules, from events
Running migrations:
  Rendering model states... DONE
  Unapplying events.0004_event_description... OK

migrate events 0003 means “bring the events app to the state after migration 0003”, which unapplies every later events migration, here only 0004. Django’s documentation warns that dependent migrations in other apps are unapplied too, and that --plan shows which will be. Apply it forward again:

uv run python manage.py migrate --plan
uv run python manage.py migrate
Operations to perform:
  Apply all migrations: accounts, admin, auth, contenttypes,
    events, registrations, sessions
Running migrations:
  Applying events.0004_event_description... OK

(The first command lists the single migration that migrate would apply.) Run the whole suite:

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

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

Step 4: The model’s own URL

Today, the views build an event’s address by hand with redirect('events:detail', event.pk), and the admin does not know where an event lives. A model method fixes both. Tests first, at the end of events/tests.py:

class AbsoluteUrlTests(TestCase):
    """An event knows the address of its own page."""

    def test_an_event_knows_its_page(self):
        event = save_event()
        self.assertEqual(event.get_absolute_url(),
                         f'/events/{event.pk}/')

    def test_the_admin_offers_view_on_site(self):
        boss = member('admin@example.org')
        boss.is_staff = boss.is_superuser = True
        boss.save()
        event = save_event()
        self.client.force_login(boss)
        response = self.client.get(
            admin_url(Event, 'change', event.pk)
        )
        self.assertContains(response, 'View on site')
uv run python manage.py test events.tests.AbsoluteUrlTests
Found 2 test(s).
Creating test database for alias 'default'...
...
AttributeError: 'Event' object has no attribute
    'get_absolute_url'
AssertionError: False is not true : Couldn't find 'View on
    site' in the following response
Ran 2 tests in ...s

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

In events/models.py, import reverse and add the method. First the import:

from django.db import models
from django.urls import reverse

Then, in Event, replace __str__ with these lines:

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        """Return the address of the event's own page."""
        return reverse('events:detail', args=[self.pk])

get_absolute_url() is the name Django looks for. With it, redirect(event) works, and the admin’s event page gains a View on site link. In events/views.py, use it in both places that redirect after a save:

            messages.success(request, 'Draft saved.')
            return redirect(event)
            messages.success(request, 'Changes saved.')
            return redirect(event)
uv run python manage.py test events.tests.AbsoluteUrlTests
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s

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

If the address ever gains a slug, or the community in its path, one method changes and every redirect follows.

Step 5: My events

Sam needs a page that lists his own events, drafts first, each with a tag for its state. The question “which events does this person organize now?” belongs in a named query, like Chapter 22’s others. Tests first. These helpers and the five tests go at the end of events/tests.py; the helpers are used again in every later step:

from django.db import (
    IntegrityError, connection, transaction,
)
from django.db.models import ProtectedError
from django.template.loader import render_to_string
from django.test import Client, SimpleTestCase, TestCase
from django.test.utils import CaptureQueriesContext
def future_draft(organizer=None, **changes):
    """Create a complete draft that starts next week."""
    fields = {
        'status': Event.Status.DRAFT,
        'starts_at': timezone.now() + timedelta(days=7),
        'description': 'Bring a laptop and a question.',
    }
    event = save_event(**(fields | changes))
    if organizer:
        event.add_organizer(organizer)
    return event


def action_url(name, event):
    """Return the address of the named action on event."""
    return reverse(f'events:{name}', args=[event.pk])


class MyEventsTests(TestCase):
    """My events lists what a member organizes now."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = editor()
        cls.sai = member('sai@example.org')
        cls.url = reverse('events:manage')
        cls.draft = future_draft(cls.sam, title='Clinic')
        cls.live = save_event(title='Meetup')
        cls.live.add_organizer(cls.sam)
        cls.off = save_event(
            title='Walk', status=Event.Status.CANCELLED
        )
        cls.off.add_organizer(cls.sam)
        save_event(title='Run by someone else')

    def test_the_address(self):
        self.assertEqual(self.url, '/events/manage/')

    def test_visitor_and_plain_member_are_kept_out(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,
        )
        self.client.force_login(self.sai)
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 403)

    def test_drafts_first_with_tags_and_only_his_own(self):
        self.client.force_login(self.sam)
        response = self.client.get(self.url)
        html = response.content.decode()
        order = [html.index(t) for t in
                 ('Clinic', 'Meetup', 'Walk')]
        self.assertEqual(order, sorted(order))
        self.assertNotContains(response, 'someone else')
        for tag in ('Draft', 'Published', 'Cancelled'):
            self.assertContains(response, f'{tag}</span>')

    def test_a_revoked_assignment_leaves_the_list(self):
        place = self.live.organizer_assignments.get()
        place.revoked_at = timezone.now()
        place.save()
        self.client.force_login(self.sam)
        response = self.client.get(self.url)
        self.assertNotContains(response, 'Meetup')

    def test_more_events_do_not_mean_more_queries(self):
        self.client.force_login(self.sam)
        with CaptureQueriesContext(connection) as few:
            self.client.get(self.url)
        for number in range(5):
            future_draft(self.sam, title=f'Extra {number}')
        with CaptureQueriesContext(connection) as many:
            self.client.get(self.url)
        self.assertEqual(len(few), len(many))

The last test counts queries. It loads the page with three events, adds five more, loads it again, and asserts that the number of queries did not change. A page that runs one extra query for every row would fail it. Run the class:

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

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

Add the query to EventQuerySet in events/models.py, just above with_places:

    def organized_by(self, user):
        """Events user organizes now, drafts first."""
        draft_first = models.Case(
            models.When(status=Event.Status.DRAFT, then=0),
            models.When(
                status=Event.Status.PUBLISHED, then=1
            ),
            default=2,
        )
        return self.filter(
            organizer_assignments__member=user,
            organizer_assignments__revoked_at__isnull=True,
        ).annotate(
            rank=draft_first
        ).order_by('rank', 'starts_at')

    def with_places(self):

Both conditions are inside one filter() call on purpose: in a single call, they must hold for the same assignment row. Two separate calls could match one assignment for the member and another, revoked one, for the event. The Case ranks drafts first, then published, then cancelled, and order_by sorts by that rank and then by start.

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

@login_required
@permission_required(
    'events.change_event', raise_exception=True
)
def event_manage(request):
    """My events: what this member organizes now."""
    events = Event.objects.organized_by(
        request.user
    ).with_places()
    return render(request, 'events/manage.html',
                  {'events': events})

The view needs change_event, and the query then shows only the events this member currently organizes. A member without the permission gets 403, and a visitor is sent to sign in. Add the address to events/urls.py, in place of the new/ pattern. The address is /events/manage/, in the family of events/new/, and the number-only pattern below cannot capture the word manage:

    path('events/new/', views.event_create,
         name='create'),
    path('events/manage/', views.event_manage,
         name='manage'),

Create events/templates/events/manage.html:

{% extends "base.html" %}
{% load tz %}

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

{% block content %}
  <h1>My events</h1>
  <ul class="event-list space-y-3">
    {% for event in events %}
      <li class="event-row card border border-base-300
                 bg-base-100 p-4">
        <p>
          <a class="font-semibold"
             href="{{ event.get_absolute_url }}">
            {{ event.title }}</a>
          {% if event.status == 'draft' %}
            <span class="badge badge-outline">Draft</span>
          {% elif event.status == 'published' %}
            <span class="badge badge-primary">
              Published</span>
          {% else %}
            <span class="badge badge-error">Cancelled</span>
          {% endif %}
        </p>
        {% timezone event.timezone %}
          <p class="text-sm">
            {{ event.starts_at|date:"D j M Y, H:i T" }}</p>
        {% endtimezone %}
        <p class="flex flex-wrap items-center gap-4 text-sm">
          <a href="{% url 'events:edit' event.pk %}">Edit</a>
        </p>
      </li>
    {% empty %}
      <li class="event-empty card border border-base-300
                 bg-base-100 p-4">
        You do not organize any events yet.</li>
    {% endfor %}
  </ul>
  <p><a href="{% url 'events:create' %}">New event</a></p>
{% endblock %}

And add the link to the navigation, in templates/includes/site_nav.html, for people who hold change_event. Replace the Events link and the line after it with these:

  <a href="{% url 'events:list' %}">Events</a>
  {% if perms.events.change_event %}
    <a href="{% url 'events:manage' %}">My events</a>
  {% endif %}
  {% if perms.events.add_event %}
uv run python manage.py test events.tests.MyEventsTests
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s

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

Rebuild the stylesheet for the tags, npm run build, then sign in as Sam in the development server (uv run python manage.py runserver) and open http://127.0.0.1:8000/events/manage/. The clinic is listed, first, with a Draft tag.

Common Error: a link before its address

Add the navigation link before the URL exists and every page shows NoReverseMatch: Reverse for 'manage' not found, because the template asks Django for an address that has not been registered. Add the pattern first, then the link, as the steps above do.

Step 6: Ready to publish

Now the first move. Two kinds of test: the model’s own, with no browser involved, and the page’s. Tests first, at the end of events/tests.py:

class ReadinessTests(TestCase):
    """What stops a draft from being published."""

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

    def test_a_complete_draft_has_no_problems(self):
        event = future_draft(self.sam)
        self.assertEqual(event.readiness_problems(), [])

    def test_every_missing_detail_is_named(self):
        event = future_draft(
            description='  ',
            starts_at=timezone.now() - timedelta(days=1),
        )
        self.assertEqual(event.readiness_problems(), [
            'Add a description.',
            'Move the start to a time in the future.',
            'Assign at least one current organizer.',
        ])

    def test_a_refused_publish_changes_nothing(self):
        event = future_draft(self.sam, description='')
        with self.assertRaises(ValidationError) as caught:
            event.publish()
        self.assertEqual(caught.exception.messages,
                         ['Add a description.'])
        event.refresh_from_db()
        self.assertEqual(event.status, Event.Status.DRAFT)


class PublishTests(TestCase):
    """Who may publish, and what publishing needs."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = editor()
        cls.sai = member('sai@example.org')

    def post(self, event, person):
        """Sign in as person and publish event."""
        self.client.force_login(person)
        return self.client.post(action_url('publish', event))

    def status(self, url):
        """Return the status code of a GET to url."""
        return self.client.get(url).status_code

    def test_an_organizer_publishes_a_complete_draft(self):
        event = future_draft(self.sam)
        response = self.post(event, self.sam)
        self.assertRedirects(
            response, event.get_absolute_url(),
            fetch_redirect_response=False,
        )
        event.refresh_from_db()
        self.assertEqual(
            event.status, Event.Status.PUBLISHED
        )
        page = self.client.get(event.get_absolute_url())
        self.assertContains(page, 'Published.')

    def test_missing_details_are_shown_and_it_stays_a_draft(
            self):
        event = future_draft(
            self.sam, description='',
            starts_at=timezone.now() - timedelta(days=1),
        )
        self.post(event, self.sam)
        page = self.client.get(event.get_absolute_url())
        self.assertContains(page, 'Add a description.')
        self.assertContains(
            page, 'Move the start to a time in the future.'
        )
        event.refresh_from_db()
        self.assertEqual(event.status, Event.Status.DRAFT)

    def test_a_member_who_may_not_edit_is_refused(self):
        event = future_draft(
            self.sam, status=Event.Status.PUBLISHED
        )
        response = self.post(event, self.sai)
        self.assertEqual(response.status_code, 403)

    def test_a_hidden_draft_is_not_found(self):
        event = future_draft(self.sam)
        response = self.post(event, self.sai)
        self.assertEqual(response.status_code, 404)
        event.refresh_from_db()
        self.assertEqual(event.status, Event.Status.DRAFT)

    def test_a_published_event_is_not_published_again(self):
        event = future_draft(
            self.sam, status=Event.Status.PUBLISHED
        )
        response = self.post(event, self.sam)
        page = self.client.get(response['Location'])
        self.assertContains(
            page, 'Only a draft can be published.'
        )

    def test_a_get_does_not_publish(self):
        event = future_draft(self.sam)
        self.client.force_login(self.sam)
        response = self.client.get(
            action_url('publish', event)
        )
        self.assertEqual(response.status_code, 405)
        self.assertEqual(response['Allow'], 'POST')
        event.refresh_from_db()
        self.assertEqual(event.status, Event.Status.DRAFT)

    def test_visitors_see_it_once_it_is_published(self):
        event = future_draft(self.sam)
        url = event.get_absolute_url()
        self.assertEqual(self.status(url), 404)
        self.post(event, self.sam)
        self.client.logout()
        self.assertEqual(self.status(url), 200)

    def test_the_button_is_for_organizers_of_drafts(self):
        draft = future_draft(self.sam)
        live = future_draft(
            self.sam, status=Event.Status.PUBLISHED
        )
        self.client.force_login(self.sam)
        page = self.client.get(draft.get_absolute_url())
        self.assertContains(
            page, f'action="{action_url("publish", draft)}"'
        )
        page = self.client.get(live.get_absolute_url())
        self.assertNotContains(
            page, f'action="{action_url("publish", live)}"'
        )
uv run python manage.py test events -k Readiness -k Publish
Found 11 test(s).
Creating test database for alias 'default'...
...
AttributeError: 'Event' object has no attribute
    'readiness_problems'
AttributeError: 'Event' object has no attribute 'publish'
Ran 11 tests in ...s

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

The model comes first. In events/models.py, add both methods to Event, just above places_taken:

    def readiness_problems(self):
        """List what stops this draft being published."""
        problems = []
        if not self.description.strip():
            problems.append('Add a description.')
        if self.starts_at <= timezone.now():
            problems.append(
                'Move the start to a time in the future.'
            )
        if not self.organizer_assignments.filter(
                revoked_at__isnull=True).exists():
            problems.append(
                'Assign at least one current organizer.'
            )
        return problems

    def publish(self):
        """Draft to published, or ValidationError."""
        if self.status != self.Status.DRAFT:
            raise ValidationError(
                'Only a draft can be published.'
            )
        problems = self.readiness_problems()
        if problems:
            raise ValidationError(problems)
        self.status = self.Status.PUBLISHED
        self.save(update_fields=['status'])

    def places_taken(self):
Four numbered cards in a column joined by downward arrows, with two outcome boxes on the right. 1, a blue Publish button card: a POST to events slash id slash publish. 2, a purple Access check card: event_to_manage answers 404 if the event is hidden and 403 if the member is not an organizer. 3, an orange event.publish card: a draft only, then readiness_problems. 4, a purple readiness_problems card: a description, a start in the future, and a current organizer. From card 4, one arrow leads to a green box, Nothing missing: the status becomes published and the message Published. A second arrow leads to a red box, Something missing: the event stays a draft, with one message per missing detail.
Figure 26.4 — Publishing, from the button to the readiness check.

readiness_problems() returns a list, not a yes or no, so a person can be told everything at once. publish() raises a ValidationError, Django’s own exception for a rule that was not met, carrying the same messages. Only a draft can be published, and nothing changes if the list is not empty. update_fields writes the one column that changed.

Now the view and its access check. The check from Chapter 25’s edit page becomes a function the edit view and every action share. In events/views.py, import ValidationError and require_POST:

from django.core.exceptions import (
    PermissionDenied, ValidationError,
)
from django.utils import timezone
from django.views.decorators.http import require_POST

Replace the start of event_edit so that it uses the shared check:

def event_to_manage(request, event_id):
    """Return the event, if this member 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
    return event


@login_required
def event_edit(request, event_id):
    """Edit the event, for those who may change it."""
    event = event_to_manage(request, event_id)
    title = event.title

And add the publish view, with the helper that turns a refusal into messages, at the end:

def refuse(request, error):
    """Show why a change was refused; nothing changed."""
    for message in error.messages:
        messages.error(request, message)


@require_POST
@login_required
def event_publish(request, event_id):
    """Publish the event, or say why not."""
    event = event_to_manage(request, event_id)
    try:
        event.publish()
    except ValidationError as error:
        refuse(request, error)
    else:
        messages.success(request, 'Published.')
    return redirect(event)

@require_POST answers any other method with a 405 response that carries an Allow: POST header, and the test that sent a GET observed exactly that. It sits outside @login_required, so a visitor who sends a GET also gets 405 and not a redirect that would end in a GET on the next page. A refusal becomes one error message per missing detail, and the redirect brings Sam back to the draft, where the messages are shown. Register the address, after the edit pattern:

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

The Publish button belongs on the draft page, which is also the preview Sam checks, so he reads the page and presses the button on the same screen. In events/templates/events/detail.html, replace the three lines of the Edit link with this block:

    {% if can_edit %}
      <div class="space-y-3 border-t border-base-300 pt-4">
        <p class="flex flex-wrap items-center gap-4">
          <a href="{% url 'events:edit' event.pk %}">
            Edit event</a>
        </p>
        {% if event.status == 'draft' %}
          <form method="post"
                action="{% url 'events:publish' event.pk %}">
            {% csrf_token %}
            <button type="submit" class="btn btn-primary">
              Publish</button>
          </form>
        {% endif %}
      </div>
    {% endif %}

The button is a form with {% csrf_token %}, never a link. Errors need their own colour: in templates/base.html, replace the messages loop so that an error message gets the alert-error class:

        {% for message in messages %}
          <p class="alert
             {% if message.level_tag == 'error' %}alert-error
             {% else %}alert-success{% endif %}">
            {{ message }}</p>
        {% endfor %}
uv run python manage.py test events -k Readiness -k Publish
Found 11 test(s).
Creating test database for alias 'default'...
...
Ran 11 tests in ...s

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

Rebuild the stylesheet with npm run build. In the browser, open the clinic as Sam. It has no description, so press Publish: the page returns with Add a description. in red, and the event is still a draft. Edit the clinic, type a description, save, and press Publish again: the page says Published., the Draft banner is gone, and the clinic is in the Events list for everyone.

Common Error: hiding the button is not a check

A template that shows the Publish button only for ready events looks safe, but a crafted POST to the address still arrives. The tests send the POST directly, with no button, and the rules live in publish(), so the answer is the same however the request is made.

Common Error: the clock has moved past the start

Publishing the clinic after 3 December 2026 is refused with Move the start to a time in the future. That is the rule working, not a fault. Use the Edit event page, move the clinic to a future date, and try again.

Step 7: Cancel, and what members see

Sam cancels a published event, and the cancelled event stays visible with a tag. Tests first. Add these at the end of events/tests.py:

class CancelTests(TestCase):
    """Cancelling published events, and who may."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = editor()
        cls.sai = member('sai@example.org')

    def cancel(self, event, person):
        """Sign in as person and cancel event."""
        self.client.force_login(person)
        return self.client.post(action_url('cancel', event))

    def test_an_organizer_cancels_a_published_event(self):
        event = future_draft(
            self.sam, status=Event.Status.PUBLISHED
        )
        response = self.cancel(event, self.sam)
        self.assertRedirects(
            response, event.get_absolute_url(),
            fetch_redirect_response=False,
        )
        event.refresh_from_db()
        self.assertEqual(
            event.status, Event.Status.CANCELLED
        )

    def test_a_draft_cannot_be_cancelled(self):
        event = future_draft(self.sam)
        response = self.cancel(event, self.sam)
        page = self.client.get(response['Location'])
        self.assertContains(
            page, 'Only a published event can be cancelled.'
        )
        event.refresh_from_db()
        self.assertEqual(event.status, Event.Status.DRAFT)

    def test_everyone_sees_the_tag_and_no_places(self):
        event = future_draft(
            self.sam, status=Event.Status.PUBLISHED
        )
        self.cancel(event, self.sam)
        self.client.logout()
        page = self.client.get(event.get_absolute_url())
        self.assertContains(page, '>Cancelled</span>')
        self.assertNotContains(page, 'places')

    def test_registrations_are_kept(self):
        event = future_draft(
            self.sam, status=Event.Status.PUBLISHED
        )
        place = Registration.objects.create(
            event=event, member=self.sai
        )
        self.cancel(event, self.sam)
        place.refresh_from_db()
        self.assertEqual(place.status,
                         Registration.Status.ACTIVE)
        self.client.force_login(self.sai)
        page = self.client.get(event.get_absolute_url())
        self.assertContains(page, '>Cancelled</span>')

    def test_it_leaves_the_event_list(self):
        event = future_draft(
            self.sam, status=Event.Status.PUBLISHED,
            title='Gone',
        )
        page = self.client.get('/events/')
        self.assertContains(page, 'Gone')
        self.cancel(event, self.sam)
        self.client.logout()
        page = self.client.get('/events/')
        self.assertNotContains(page, 'Gone')

    def test_a_non_organizer_and_a_get_are_refused(self):
        event = future_draft(
            self.sam, status=Event.Status.PUBLISHED
        )
        response = self.cancel(event, self.sai)
        self.assertEqual(response.status_code, 403)
        self.client.force_login(self.sam)
        response = self.client.get(
            action_url('cancel', event)
        )
        self.assertEqual(response.status_code, 405)
        event.refresh_from_db()
        self.assertEqual(
            event.status, Event.Status.PUBLISHED
        )

One Chapter 24 test changes in place, because it expected a cancelled event to be hidden. In EventDetailTests, rename test_unpublished_events_are_hidden to test_drafts_are_hidden, and replace the loop over the two statuses with a draft alone:

        event = save_event(status=Event.Status.DRAFT)
        response = self.client.get(f'/events/{event.pk}/')
        self.assertEqual(response.status_code, 404)
uv run python manage.py test events -k Cancel -k EventDetail
Found 11 test(s).
Creating test database for alias 'default'...
...
Ran 11 tests in ...s

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

In events/models.py, change is_visible_to so that only a draft is hidden. Replace its first lines:

    def is_visible_to(self, user):
        """Whether user may see this event.

        Published and cancelled: everyone. A draft:
        organizers and holders of view_event.
        """
        if self.status != self.Status.DRAFT:
            return True

And add cancel above places_taken:

    def cancel(self):
        """Cancel if published, or raise ValidationError."""
        if self.status != self.Status.PUBLISHED:
            raise ValidationError(
                'Only a published event can be cancelled.'
            )
        self.status = self.Status.CANCELLED
        self.save(update_fields=['status'])

    def places_taken(self):

At the end of events/views.py, add the view, then its address after the publish pattern:

@require_POST
@login_required
def event_cancel(request, event_id):
    """Cancel the event, or say why not."""
    event = event_to_manage(request, event_id)
    try:
        event.cancel()
    except ValidationError as error:
        refuse(request, error)
    else:
        messages.success(request, 'Event cancelled.')
    return redirect(event)
    path('events/<int:event_id>/cancel/',
         views.event_cancel, name='cancel'),

Three changes to events/templates/events/detail.html. The banner now says Cancelled for a cancelled event and Draft for a draft:

    {% if event.status == 'draft' %}
      <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>
    {% elif event.status == 'cancelled' %}
      <p><span class="badge badge-error">Cancelled</span>
        This event is off.</p>
    {% endif %}

A cancelled event shows no line about places, because nothing can be taken. Replace the places condition:

    {% if now < event.ends_at %}
      {% if event.status != 'cancelled' %}
        <p>{% include "events/places.html" %}</p>
      {% endif %}
    {% endif %}

And the actions block gains the Cancel form for a published event:

        {% if event.status == 'draft' %}
          <form method="post"
                action="{% url 'events:publish' event.pk %}">
            {% csrf_token %}
            <button type="submit" class="btn btn-primary">
              Publish</button>
          </form>
        {% elif event.status == 'published' %}
          <form method="post"
                action="{% url 'events:cancel' event.pk %}">
            {% csrf_token %}
            <button type="submit" class="btn btn-outline">
              Cancel event</button>
            <span class="text-sm">Cancelling cannot be
              undone. Members keep their places.</span>
          </form>
        {% endif %}
uv run python manage.py test events -k Cancel -k EventDetail
Found 11 test(s).
Creating test database for alias 'default'...
...
Ran 11 tests in ...s

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

The Cancel button sits beside a plain sentence that cancelling cannot be undone and that members keep their places, which is true: the registrations are untouched, and Chapter 31 and Chapters 43 and 44 decide what members are told. Rebuild the stylesheet with npm run build.

Note: the old test and the new rule

The Chapter 24 test did not become wrong by accident. It recorded a decision, that cancelled events are hidden like drafts, and this chapter changes the decision on purpose. When a rule changes, the test that held the old rule changes in the same step, and you say so, as here.

Step 8: Delete a draft

Deleting is the only move that loses data, so it has the most refusals. Tests first, at the end of events/tests.py:

class DeleteTests(TestCase):
    """Only a draft nobody registered for is deleted."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = editor()
        cls.sai = member('sai@example.org')

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

    def kept(self, event):
        """Return whether event is still in the database."""
        return Event.objects.filter(pk=event.pk).exists()

    def test_a_get_shows_the_page_and_deletes_nothing(self):
        draft = future_draft(self.sam)
        response = self.client.get(
            action_url('delete', draft)
        )
        self.assertTemplateUsed(
            response, 'events/delete.html'
        )
        self.assertContains(response, 'cannot be undone')
        self.assertTrue(self.kept(draft))

    def test_a_post_deletes_the_draft_and_assignments(self):
        draft = future_draft(self.sam)
        response = self.client.post(
            action_url('delete', draft)
        )
        self.assertRedirects(
            response, reverse('events:manage'),
            fetch_redirect_response=False,
        )
        self.assertFalse(self.kept(draft))
        self.assertFalse(
            OrganizerAssignment.objects.exists()
        )
        page = self.client.get(reverse('events:manage'))
        self.assertContains(page, 'Draft deleted.')

    def test_a_draft_with_registrations_is_kept(self):
        draft = future_draft(self.sam)
        Registration.objects.create(
            event=draft, member=self.sai
        )
        response = self.client.post(
            action_url('delete', draft)
        )
        page = self.client.get(response['Location'])
        self.assertContains(page, 'has registrations')
        self.assertTrue(self.kept(draft))
        places = draft.organizer_assignments.count()
        self.assertEqual(places, 1)

    def test_published_and_cancelled_events_are_kept(self):
        for status in (Event.Status.PUBLISHED,
                       Event.Status.CANCELLED):
            with self.subTest(status=status):
                event = future_draft(self.sam, status=status)
                for send in (self.client.get,
                             self.client.post):
                    response = send(
                        action_url('delete', event)
                    )
                    code = response.status_code
                    self.assertEqual(code, 302)
                self.assertTrue(self.kept(event))

    def test_a_non_organizer_is_refused(self):
        event = future_draft(
            self.sam, status=Event.Status.PUBLISHED
        )
        self.client.force_login(self.sai)
        for send in (self.client.get, self.client.post):
            response = send(action_url('delete', event))
            self.assertEqual(response.status_code, 403)
        self.assertTrue(self.kept(event))

    def test_another_method_is_refused(self):
        draft = future_draft(self.sam)
        url = action_url('delete', draft)
        response = self.client.delete(url)
        self.assertEqual(response.status_code, 405)
        self.assertTrue(self.kept(draft))
uv run python manage.py test events.tests.DeleteTests
Found 6 test(s).
Creating test database for alias 'default'...
...
Ran 6 tests in ...s

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

In events/models.py, import transaction and add the method. Replace the import line:

from django.db import models, transaction
from django.urls import reverse
    def delete_draft(self):
        """Delete a draft nobody registered for."""
        if self.status != self.Status.DRAFT:
            raise ValidationError(
                'Only a draft can be deleted.'
            )
        if self.registrations.exists():
            raise ValidationError(
                'This draft has registrations, so it '
                'is kept.'
            )
        with transaction.atomic():
            self.organizer_assignments.all().delete()
            self.delete()

    def places_taken(self):
Four numbered cards down the left and two boxes on the right. 1, a blue GET delete page card: it shows the draft and says it cannot be undone, and nothing changes. 2, a blue POST card: the button sends the token. 3, an orange delete_draft card: a draft only, with no registrations. 4, a green One transaction card: the draft’s organizer assignments are deleted first, then the event, so both happen or neither. A red Refused box beside card 3 says that for a published or cancelled event, or one with a registration, there is a message and every row stays. A purple Why the order box beside card 4 says each assignment protects its event, so the event cannot be deleted while one remains.
Figure 26.5 — Deleting a draft, and why the assignments go first.

Inside transaction.atomic(), the assignments go first and the event second. If the second delete fails, the first is undone, and nothing is half deleted. In events/views.py, the import for the methods the view allows changes:

from django.views.decorators.http import (
    require_http_methods, require_POST,
)
@require_http_methods(['GET', 'POST'])
@login_required
def event_delete(request, event_id):
    """Confirm, then delete a draft; or say why not."""
    event = event_to_manage(request, event_id)
    if request.method == 'POST':
        try:
            event.delete_draft()
        except ValidationError as error:
            refuse(request, error)
            return redirect(event)
        messages.success(request, 'Draft deleted.')
        return redirect('events:manage')
    if event.status != Event.Status.DRAFT:
        refuse(request, ValidationError(
            'Only a draft can be deleted.'
        ))
        return redirect(event)
    return render(request, 'events/delete.html',
                  {'event': event})

The view allows GET and POST only. A GET shows the confirmation page for a draft, and for anything else it explains and redirects. A POST deletes, and sends the person to My events. Add the address after the cancel pattern:

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

Create events/templates/events/delete.html:

{% extends "base.html" %}

{% block title %}Delete {{ event.title }} |
  Otahque{% endblock %}

{% block content %}
  <h1>Delete {{ event.title }}?</h1>
  <p>This draft and its organizer list will be removed. It
     cannot be undone.</p>
  <form method="post" class="card space-y-4 border
        border-base-300 bg-base-100 p-6">
    {% csrf_token %}
    <button type="submit" class="btn btn-error">
      Delete draft</button>
  </form>
  <p>
    <a href="{{ event.get_absolute_url }}">Keep it</a>
  </p>
{% endblock %}

The link to it goes on the event page for drafts, and on the My events page. In detail.html, replace the Edit link with these lines, and in manage.html, its Edit link:

          <a href="{% url 'events:edit' event.pk %}">
            Edit event</a>
          {% if event.status == 'draft' %}
            <a href="{% url 'events:delete' event.pk %}">
              Delete draft</a>
          {% endif %}
          <a href="{% url 'events:edit' event.pk %}">Edit</a>
          {% if event.status == 'draft' %}
            <a href="{% url 'events:delete' event.pk %}">
              Delete</a>
          {% endif %}

A link to the delete page is safe: it is a GET that only reads. Run the class, then rebuild the stylesheet with npm run build:

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

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

Common Error: deleting the event before its assignments

Call self.delete() first and Django raises ProtectedError, the message you saw in Step 2, and nothing is deleted. Delete the assignments first, inside the same transaction, as delete_draft() does.

Step 9: Copy an event

Sam’s clinic runs every Thursday. A copy creates a new draft with the same title, description, place, time zone, capacity, and length, and asks only for the new start. It never copies registrations, status, or other organizers: the copier becomes the organizer. A cancelled event can be copied, which is how it is run again. Tests first, at the end of events/tests.py:

class CopyTests(TestCase):
    """A copy is a new draft starting when asked."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = editor()
        cls.sai = member('sai@example.org')
        cls.raj = editor('raj@example.org')

    def test_a_copy_is_a_new_draft_with_form_details(self):
        event = future_draft(
            self.sam, status=Event.Status.PUBLISHED,
            title='Weekly clinic', timezone='Asia/Kolkata',
            capacity=25, location='Online',
        )
        event.add_organizer(self.raj)
        Registration.objects.create(
            event=event, member=self.sai
        )
        self.client.force_login(self.sam)
        response = self.client.post(
            action_url('copy', event),
            {'starts_at': '2027-02-04T19:00'},
        )
        copy = Event.objects.exclude(pk=event.pk).get()
        self.assertRedirects(
            response, reverse('events:edit', args=[copy.pk]),
            fetch_redirect_response=False,
        )
        self.assertEqual(copy.status, Event.Status.DRAFT)
        self.assertEqual(
            (copy.title, copy.description, copy.location,
             copy.timezone, copy.capacity),
            (event.title, event.description, event.location,
             event.timezone, event.capacity),
        )
        self.assertEqual(copy.ends_at - copy.starts_at,
                         event.ends_at - event.starts_at)
        self.assertEqual(
            copy.starts_at,
            datetime(2027, 2, 4, 13, 30, tzinfo=UTC),
        )
        self.assertFalse(copy.registrations.exists())
        members = [a.member for a in
                   copy.organizer_assignments.all()]
        self.assertEqual(members, [self.sam])

    def test_a_cancelled_event_can_be_copied(self):
        event = future_draft(
            self.sam, status=Event.Status.CANCELLED
        )
        self.client.force_login(self.sam)
        self.client.post(action_url('copy', event),
                         {'starts_at': '2027-02-04T19:00'})
        self.assertEqual(Event.objects.count(), 2)
        event.refresh_from_db()
        self.assertEqual(
            event.status, Event.Status.CANCELLED
        )

    def test_a_bad_start_copies_nothing(self):
        event = future_draft(self.sam)
        self.client.force_login(self.sam)
        page = self.client.get(action_url('copy', event))
        self.assertContains(page, 'type="datetime-local"')
        response = self.client.post(
            action_url('copy', event), {'starts_at': ''}
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(Event.objects.count(), 1)

    def test_a_non_organizer_is_refused(self):
        event = future_draft(
            self.sam, status=Event.Status.PUBLISHED
        )
        self.client.force_login(self.sai)
        for send in (self.client.get, self.client.post):
            response = send(action_url('copy', event))
            self.assertEqual(response.status_code, 403)
        self.assertEqual(Event.objects.count(), 1)
uv run python manage.py test events.tests.CopyTests
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s

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

The form asks for one value, read in the event’s own zone with Chapter 24’s in_zone(). Add it at the end of events/forms.py:

class CopyForm(forms.Form):
    """The one thing a copy asks for: when it starts."""

    starts_at = forms.DateTimeField(
        label='New start', widget=local_input(),
    )

    def __init__(self, *args, event, **kwargs):
        """Say which zone the new start is read in."""
        super().__init__(*args, **kwargs)
        self.event = event
        self.fields['starts_at'].help_text = (
            f'Read in {event.timezone}. The copy lasts as '
            'long as the original.'
        )

    def clean_starts_at(self):
        """Read the new start in the event's time zone."""
        return in_zone(self.cleaned_data['starts_at'],
                       self.event.timezone)

In events/models.py, add the method above places_taken:

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

        It starts at starts_at, organized by member.
        """
        with transaction.atomic():
            copy = Event.objects.create(
                title=self.title,
                description=self.description,
                timezone=self.timezone,
                location=self.location,
                capacity=self.capacity,
                starts_at=starts_at,
                ends_at=starts_at + (
                    self.ends_at - self.starts_at
                ),
            )
            copy.add_organizer(member)
        return copy

    def places_taken(self):

The copy’s end is its start plus the original’s length, so a two-hour event stays two hours. In events/views.py, import CopyForm and add the view at the end:

from .forms import CopyForm, EventForm
@require_http_methods(['GET', 'POST'])
@login_required
def event_copy(request, event_id):
    """Ask for a start, then copy the event as a draft."""
    event = event_to_manage(request, event_id)
    if request.method == 'POST':
        form = CopyForm(request.POST, event=event)
        if form.is_valid():
            copy = event.copy_as_draft(
                request.user, form.cleaned_data['starts_at']
            )
            messages.success(
                request, 'Copied as a new draft.'
            )
            return redirect('events:edit', copy.pk)
    else:
        form = CopyForm(event=event)
    return render(request, 'events/copy.html',
                  {'event': event, 'form': form})

This view, unlike publish and cancel, allows a GET: the page that asks for the new start only reads, and the POST creates the draft. Add the address, then the template:

    path('events/<int:event_id>/copy/', views.event_copy,
         name='copy'),
{% extends "base.html" %}

{% block title %}Copy {{ event.title }} |
  Otahque{% endblock %}

{% block content %}
  <h1>Copy {{ event.title }}</h1>
  <p>Otahque saves a new draft with the same title,
     description, place, time zone, capacity, and length.
     Registrations and other organizers are not copied.</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 copy as a draft</button>
  </form>
  <p>
    <a href="{{ event.get_absolute_url }}">
      Back to the event</a>
  </p>
{% endblock %}

And the links, in detail.html and in manage.html, next to Edit:

          <a href="{% url 'events:edit' event.pk %}">
            Edit event</a>
          <a href="{% url 'events:copy' event.pk %}">
            Copy as a new draft</a>
          <a href="{% url 'events:edit' event.pk %}">Edit</a>
          <a href="{% url 'events:copy' event.pk %}">Copy</a>
uv run python manage.py test events.tests.CopyTests
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s

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

In the browser, open a published event as Sam, choose Copy as a new draft, type next Thursday at the same time, and save. You land on the new draft’s edit page with a copy of everything but the date.

Step 10: Prove the token on every action, record the design, and commit

Each action changes data, so each needs Chapter 24’s proof: a client that enforces the CSRF check is refused without a token, and accepted with the page’s. Add this at the end of events/tests.py:

class ActionCsrfTests(TestCase):
    """Each action refuses a post without the token."""

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

    def send(self, name, event, data=None):
        """Post without, then with, the page's token."""
        data = data or {}
        browser = Client(enforce_csrf_checks=True)
        browser.force_login(self.sam)
        url = action_url(name, event)
        refused = browser.post(url, data)
        self.assertEqual(refused.status_code, 403)
        self.assertEqual(Event.objects.count(), 1)
        page = browser.get(url if name == 'copy'
                           else event.get_absolute_url())
        token = str(page.context['csrf_token'])
        sent = browser.post(
            url, data | {'csrfmiddlewaretoken': token}
        )
        self.assertEqual(sent.status_code, 302)

    def test_publish_needs_the_token(self):
        event = future_draft(self.sam)
        self.send('publish', event)
        event.refresh_from_db()
        self.assertEqual(
            event.status, Event.Status.PUBLISHED
        )

    def test_cancel_needs_the_token(self):
        event = future_draft(
            self.sam, status=Event.Status.PUBLISHED
        )
        self.send('cancel', event)
        event.refresh_from_db()
        self.assertEqual(
            event.status, Event.Status.CANCELLED
        )

    def test_delete_needs_the_token(self):
        event = future_draft(self.sam)
        self.send('delete', event)
        self.assertFalse(Event.objects.exists())

    def test_copy_needs_the_token(self):
        event = future_draft(self.sam)
        self.send('copy', event,
                  {'starts_at': '2027-02-04T19:00'})
        self.assertEqual(Event.objects.count(), 2)
uv run python manage.py test events.tests.ActionCsrfTests
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s

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

Write the design down in docs/design/event-states.md, as Chapters 24 and 25 did for their pages. It holds Table 26.1, what each state shows, the request paths, and what is left open:

# Event states: low-level design

Status: Drafted in Chapter 26, for review. Not approved.
Who may act: current organizers who hold events.change_event
(Event.can_be_edited_by, Chapter 25). Chapter 30 replaces
the rule behind that one method with roles.

## States and moves

- publish: draft to published. Refused when it is not a
  draft, has no description, does not start in the future,
  or has no current organizer.
- cancel: published to cancelled. Refused when not published.
- delete: a draft is removed. Refused when it is not a draft,
  or when any registration exists.
- copy: any state to a new draft. Refused when the new start
  is missing or unreadable.

- There is no unpublish. Cancelled is final: run the event
  again by copying it.
- Every move except the delete page's GET is a POST. The
  views for publish and cancel answer a GET with 405.
- A refused move changes nothing and tells the member why
  (one message per missing detail).

## What each state shows

- Draft: organizers and view_event holders; a Draft banner.
- Published: everyone; in the upcoming and past lists.
- Cancelled: everyone who has the address, with a
  Cancelled tag and no places line; not in either list.
  Registrations stay as they are.

## Request path

- POST events/<id>/publish/ and .../cancel/: require_POST,
  login_required, event_to_manage (404 hidden, 403
  refused), then event.publish() or event.cancel();
  ValidationError messages become error messages; 302 to
  the event.
- GET events/<id>/delete/: the confirmation page (a draft
  only). POST: event.delete_draft() removes the draft's
  organizer assignments, then the event, in one
  transaction; 302 to My events.
- GET/POST events/<id>/copy/: asks for the new start in the
  event's zone; event.copy_as_draft(user, starts_at) copies
  title, description, place, time zone, capacity, and
  length; never registrations, status, or other organizers;
  302 to the new draft's edit page.
- GET events/manage/: permission_required(change_event);
  Event.objects.organized_by(user): current assignments
  only, drafts first.

## Open

- Audit records of each move: Chapter 30.
- Telling members of a cancellation: Chapters 43-44.
- A version check for two organizers acting at once:
  Chapter 33.
- The cover image joins what a copy carries: Chapter 42.

Last checks and the commit. No migration is waiting, the project’s own check is clean, and the whole suite passes:

uv run python manage.py makemigrations --check --dry-run
uv run python manage.py check
uv run python manage.py test
No changes detected
System check identified no issues (0 silenced).
Found 165 test(s).
Creating test database for alias 'default'...
...
Ran 165 tests in ...s

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

Commit the work, with the stylesheet that npm run build produced:

git add .
git status --short
git commit -m "Publish, cancel, delete, and copy events"
 M events/admin.py
 M events/forms.py
 M events/models.py
 M events/templates/events/detail.html
 M events/tests.py
 M events/urls.py
 M events/views.py
 M static/otahque/site.css
 M templates/base.html
 M templates/includes/site_nav.html
?? docs/design/event-states.md
?? events/migrations/0004_event_description.py
?? events/templates/events/copy.html
?? events/templates/events/delete.html
?? events/templates/events/manage.html
?? templates/django/forms/widgets/textarea.html

Table 26.2 lists what to do when a step does not go as described. Every route leaves your work in place.

Table 26.2 — When a step goes wrong
Symptom Likely cause Recovery
NoReverseMatch for manage, publish, cancel, delete, or copy The link or redirect was added before the pattern in urls.py Add the pattern, matching the name in Table 26.3, and reload
A new test passes before the code exists The test asserts something already true Check what it asserts, and make it fail first by naming the missing behaviour
Publish says Move the start to a time in the future The clinic's start has passed Edit the clinic's start, then publish
Delete does nothing and shows Only a draft can be deleted The event is published or cancelled Cancel it instead; only a draft is deleted
The Cancel button or tags look unstyled The stylesheet was not rebuilt Run npm run build, then reload
A migration refuses to apply or roll back Another migration depends on it, or the database holds data it cannot convert Run migrate --plan, read the list, and compare your files with a separate copy of the reference repository
Table 26.3 — The addresses this chapter adds
Address What it does Name
/events/manage/ The organizer's own events, drafts first events:manage
/events/<id>/publish/ POST: publish a ready draft events:publish
/events/<id>/cancel/ POST: cancel a published event events:cancel
/events/<id>/delete/ GET: confirm; POST: delete a draft events:delete
/events/<id>/copy/ GET: ask for a start; POST: save a copy events:copy
PAGE 003

Verify Your Work

Work through Table 26.4 from the folder that holds manage.py. The test rows come first: they hold the chapter’s rules in place whatever rows your database holds.

Table 26.4 — Verification checklist for Chapter 26
Check Command or action Expected result
Starting point uv run python manage.py test Found 124 test(s); OK
Tests fail first Each step's new classes, before the code FAILED, with errors or failures
Migration read sqlmigrate events 0004, and with --backwards The SQL, forward and back, printed and not run
Migration applied and undone migrate; migrate events 0003; migrate 0004 applied, unapplied, applied
Tests pass uv run python manage.py test Found 165 test(s); OK
No migration waiting makemigrations --check --dry-run No changes detected
Draft not ready Sign in as Sam, Publish the clinic with no description Add a description. in red; still a draft
Draft published Add a description, Publish Published.; no Draft banner; in the Events list
Cancelled tag Cancel a published event, open it as a visitor A Cancelled tag, no places line, not in the lists
Delete is a form Open the Delete page, then Delete draft A confirmation page, then Draft deleted.
GET changes nothing /events/6/publish/ typed in the address bar 405, and the event is unchanged
Copy Copy as a new draft with next Thursday's date A new draft with the old details
Phone width Device toolbar, 390 px The buttons wrap; no sideways scroll
Committed git status --short No output
Not verified macOS, Linux, WSL; Firefox, Safari; screen readers Readers on those systems

The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 25 checkpoint, every listing applied in the order printed, with each step’s new tests run before the code and after it. The browser rows were walked through in Microsoft Edge against the development server, at a phone’s width and a desktop’s. The final files were compared with app/ and are identical.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 3 Sam presses Publish on the clinic, which has no description and starts next week. What does the page show, what is stored, and where does the rule live?

Flip to check your answerFold answer back

Answer. The page returns to the draft with Add a description. in an error message, and the event is still a draft. The rule lives in the model: readiness_problems() returns the message and publish() raises it before changing the status, so the answer is the same whether the request comes from a button, a crafted POST, or the shell.

Que. 4 A crawler follows the links on Sam’s pages. Why does that not delete the draft, publish it, or cancel it?

Flip to check your answerFold answer back

Answer. The delete link opens a confirmation page, which only reads. Publishing and cancelling are POST-only views, so a GET to their addresses answers 405 and changes nothing. A POST also needs the CSRF token that only Otahque’s own forms carry.

Que. 5 Why does delete_draft() delete the organizer assignments first, inside transaction.atomic()?

Flip to check your answerFold answer back

Answer. Each assignment protects its event with PROTECT, so the event cannot be deleted while one remains. Deleting them first makes the event deletable, and the transaction makes the two deletes one unit: if the second fails, the first is undone.

Que. 6 Table 26.1 has no way back from cancelled. How does Sam run a cancelled event again, and what carries over?

Flip to check your answerFold answer back

Answer. He copies it to a new draft, with a new start. The title, description, place, time zone, capacity, and length carry over. Registrations, the status, and other organizers do not, and Sam becomes the new draft’s organizer.

Que. 7 You apply 0004, then run uv run python manage.py migrate events 0003. What happens to the description column and to what was typed in it, and what would you do instead on a database that holds real events?

Flip to check your answerFold answer back

Answer. The migration is unapplied: the column is dropped, and the descriptions in it are lost, as sqlmigrate events 0004 --backwards shows. On a database with real data, you would not roll back. You would fix forward with a new migration, after reading the SQL of each step with sqlmigrate.

Mini-Challenge

Que. 8 Predict what readiness_problems() returns for three drafts: A, complete and starting in seven days; B, with no description, started yesterday, with Sam as organizer; and C, with a description of three spaces, starting in seven days, and no organizer. Then check with the file below, run with uv run python manage.py shell -c "exec(open('challenge.py').read())".

Flip to check your answerFold answer back

Answer. A has no problems. B has two: Add a description. and Move the start to a time in the future. C has two: a description of spaces counts as missing, and there is no current organizer. The file rolls its work back, so your rows are unchanged:

from datetime import timedelta

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

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

sam = User.objects.get(email='sam@example.org')
DRAFTS = [('A', 7, 'Bring a laptop.', True),
          ('B', -1, '', True),
          ('C', 7, '   ', False)]
with transaction.atomic():
    for title, days, description, organized in DRAFTS:
        start = timezone.now() + timedelta(days=days)
        event = Event.objects.create(
            title=title, description=description,
            timezone='Europe/London', starts_at=start,
            ends_at=start + timedelta(hours=1),
            location='Online', capacity=20,
        )
        if organized:
            event.add_organizer(sam)
        problems = event.readiness_problems()
        print(title, len(problems), 'problems')
        for problem in problems:
            print('  ' + problem)
    transaction.set_rollback(True)
A 0 problems
B 2 problems
  Add a description.
  Move the start to a time in the future.
C 2 problems
  Add a description.
  Assign at least one current organizer.

What We Learned

  • An event has three states and a short list of moves; anything not on the list is refused, and each refusal changes nothing.
  • A change of state is a POST, behind a form with the CSRF token; a GET only reads, and a view that accepts only POST answers a GET with 405.
  • Readiness is stricter than validity, and it lives in the model: readiness_problems() lists what is missing, and publish() refuses until the list is empty.
  • A new text column is TextField(blank=True), with the empty string as its “no data”; sqlmigrate shows a migration’s SQL without running it, and migrate app number undoes migrations, at the cost of the data in what is dropped.
  • A protected foreign key stops a delete until the rows that point at it are gone, so a draft is deleted with its assignments, in one transaction.
  • Delete asks first, on a page that only reads, and refuses everything but a draft with no registrations; cancelling keeps the story that deleting would erase.
  • get_absolute_url() lets the model say where it lives, for redirects and for the admin.
  • One query with both conditions inside one filter(), and a test that counts queries, keep a list page honest.
  • One method, can_be_edited_by(), answers who may act; Chapter 30 will plug roles into it.

Key terms

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

Table 26.5 — Key terms from Chapter 26
Term Meaning
State machine A list of states and the moves allowed between them.
Readiness What must be true before a draft is published; stricter than validity.
Safe method A request method, such as GET, defined as read-only.
405 Method Not Allowed The answer to a method a view does not accept, with an Allow header.
POST-only view A view that accepts only POST, here with require_POST.
Confirmation page A GET page that asks first; only its POST changes data.
Transaction A group of changes that all happen or none do.
ProtectedError The exception for deleting a row that a protected foreign key points at.
get_absolute_url() The model method that returns the object's own address.
sqlmigrate The command that prints a migration's SQL without running it.
Rollback (migration) Unapplying migrations with migrate app number; it drops what they added.
Copy as a new draft A new event made from an old one's form details, with none of its history.

Readiness checkpoint: you are ready for Chapter 27 when all 165 tests pass, makemigrations --check --dry-run prints No changes detected, signing in as Sam shows My events in the navigation, the clinic can be published once it has a description and a future start, a published event can be cancelled and then shows a Cancelled tag to visitors, a draft deletes only through its confirmation page, a copy opens as a new draft, and a GET to a publish, cancel, or delete-by-POST address changes nothing.

Git Commit

Your Chapter 26 work was committed in Step 10. For the record, these were the commands, in any shell, beside manage.py:

git add .
git status --short
git commit -m "Publish, cancel, delete, and copy events"

The commit holds the description field and its migration, the model’s get_absolute_url, organized_by, readiness_problems, publish, cancel, delete_draft, and copy_as_draft, five views with their addresses, three templates and the textarea widget template, the changed event page, My events link, and messages, the rebuilt stylesheet, the design note, forty-one new tests, and one test changed in place.

PAGE 005

Test Your Knowledge: Interview Questions

These seven questions rehearse the chapter at interview level, from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead to a larger application with a team: attempt them now, and return to them after Chapters 30 and 33. L6 and L7 are about migrations, and you can answer them now with the commands from Step 3. They are extension questions, not a gate to the next chapter.

L1 (Junior): Why must publishing or deleting never happen on a GET request?

What the interviewer is testing: Do you know what a safe method is, and what a link, a prefetch, and a crawler do with one?

Flip to check your answerFold answer back

Perfect answer: A GET is defined as read-only, and the web relies on that. Browsers prefetch links, search crawlers follow every link they find, and people paste addresses into chats, which open previews. If a GET changes data, each of them can publish or delete an event without anyone deciding to. So a change goes in a POST, sent by a form, and for an organizer’s page it also carries the CSRF token. A view that takes only POST answers anything else with 405 and an Allow header.

Behind the scenes:

publish and cancel -> require_POST -> 405, Allow: POST
delete page        -> shows a confirmation; deletes nothing

Code proof: a signed-in Sam opens the three addresses with GET, inside a transaction that is rolled back:

from django.db import transaction
from django.test import Client
from django.test.utils import setup_test_environment

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

setup_test_environment()
sam = User.objects.get(email='sam@example.org')
with transaction.atomic():
    web = Client()
    web.force_login(sam)
    for name in ('publish', 'cancel'):
        reply = web.get(f'/events/6/{name}/')
        print(name, reply.status_code, reply['Allow'])
    page = web.get('/events/6/delete/')
    print('delete page', page.status_code)
    print('still there:', Event.objects.filter(pk=6).exists())
    clinic = Event.objects.get(pk=6)
    print('status:', clinic.status)
    transaction.set_rollback(True)
Method Not Allowed (GET): /events/6/publish/
publish 405 POST
Method Not Allowed (GET): /events/6/cancel/
cancel 405 POST
delete page 200
still there: True
status: draft

Common mistakes:

  • Writing <a href="/events/6/delete/"> and having that view delete.
  • Hiding the button instead of refusing the method.
  • Forgetting that a link with onclick JavaScript still sends a GET when JavaScript is off.

Follow-up the interviewer might ask:

  • “Is a POST enough, by itself, to protect a delete?”
  • “What does the Allow header tell a client?”

L2 (Mid-Level): Predict what happens when Sam presses Publish on a draft with no description that starts next week.

What the interviewer is testing: Can you trace a refused publish through the access check, the model, and the page, and say what is stored?

Flip to check your answerFold answer back
Five numbered steps. Sam presses Publish on a draft with no description that starts next week. He organizes it and holds change_event, so the access check passes. readiness_problems returns one message, Add a description. publish raises it and the status stays draft. A redirect to the draft page shows the message.
Figure 26.6 — A refused publish, from the button to the message.

Perfect answer: The POST reaches event_publish, and the access check passes: Sam is a current organizer and holds change_event. publish() first checks the status, which is a draft, then calls readiness_problems(). The start is next week and an organizer exists, so the list holds one message, Add a description. publish() raises a ValidationError before changing anything, the view turns the message into an error message and redirects to the draft, and the status is still draft.

Behind the scenes:

access check        -> passes
status is draft     -> continues
readiness_problems  -> ['Add a description.']
publish()           -> raises; no write
redirect            -> the draft page shows the message

Code proof: the same draft in the shell, rolled back afterwards:

from datetime import timedelta

from django.core.exceptions import ValidationError
from django.db import transaction
from django.utils import timezone

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

sam = User.objects.get(email='sam@example.org')
with transaction.atomic():
    soon = timezone.now() + timedelta(days=7)
    draft = Event.objects.create(
        title='Next week', timezone='Europe/London',
        starts_at=soon, ends_at=soon + timedelta(hours=1),
        location='Online', capacity=20,
    )
    draft.add_organizer(sam)
    print(draft.readiness_problems())
    try:
        draft.publish()
    except ValidationError as error:
        print('refused:', error.messages)
    draft.refresh_from_db()
    print('status:', draft.status)
    transaction.set_rollback(True)
['Add a description.']
refused: ['Add a description.']
status: draft

Common mistakes:

  • Returning only the first problem, so the person fixes one, tries again, and meets the next.
  • Checking readiness in the template, so the button is hidden but a crafted POST works.
  • Saving first and then checking, which leaves a published event in the database for a moment.

Follow-up the interviewer might ask:

  • “How would you show the problems before the person presses the button?”
  • “Where would you add the registration window later?”

L3 (Senior): Defend refusing to delete published events, and cancelling them instead.

What the interviewer is testing: Do you weigh what a delete destroys against what a cancel keeps, and know which layer is the last line?

Flip to check your answerFold answer back
Five numbered steps. The goal is that members who registered are never left with nothing. A published event may have registrations, which are history. Deleting is refused when any registration exists. Cancelling keeps every row and shows a Cancelled tag. Deleted rows cannot be recovered, while cancelled rows tell the story.
Figure 26.7 — Why a published event is cancelled and not deleted.

Perfect answer: A published event has been public, and members may hold places in it. Deleting it would erase their registrations, which are the record of who planned to come, and Sai would find a “not found” page where she had a place. Cancelling keeps every row, tags the page so everyone learns what happened, and leaves the history for later chapters, such as the notification email and Chapter 31’s reports. The model enforces it twice: delete_draft() refuses anything but a draft, and the database refuses to delete an event while a registration points at it.

Behind the scenes:

delete_draft() -> refused: only a draft
event.delete() -> refused: a registration protects it
cancel()       -> allowed; every row stays

Code proof: a published event with one registration, rolled back afterwards:

from datetime import timedelta

from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import ProtectedError
from django.utils import timezone

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

sai = User.objects.get(email='sai@example.org')
with transaction.atomic():
    soon = timezone.now() + timedelta(days=7)
    event = Event.objects.create(
        title='Meetup', timezone='Europe/London',
        starts_at=soon, ends_at=soon + timedelta(hours=1),
        location='Online', capacity=20, status='published',
    )
    Registration.objects.create(event=event, member=sai)
    try:
        event.delete_draft()
    except ValidationError as error:
        print('delete_draft:', error.messages[0])
    try:
        event.delete()
    except ProtectedError:
        print('delete(): ProtectedError')
    event.cancel()
    print('after cancel:', event.status,
          event.registrations.count())
    transaction.set_rollback(True)
delete_draft: Only a draft can be deleted.
delete(): ProtectedError
after cancel: cancelled 1

Common mistakes:

  • Deleting published events with a cascade, so the registrations go with them.
  • Adding a soft-delete flag for a draft nobody has seen.
  • Treating the database’s protection as the first line, when a clear message in the model is kinder.

Follow-up the interviewer might ask:

  • “When would you want a soft delete?”
  • “What would you tell the members who hold places?”

L4 (Staff): A crawler deleted rows in production by following links. Diagnose and fix.

What the interviewer is testing: Can you find a state-changing GET, fix it without breaking the page, and prove the fix with a test?

Flip to check your answerFold answer back
Five numbered steps. Rows vanish in production after a crawler visits. A delete link is an anchor with an href, so every GET deletes. Move the delete to a POST behind a confirmation page. Require POST, keep the CSRF token, and test that a GET deletes nothing. Restore from a backup, and add the test to the suite.
Figure 26.8 — Finding and removing a delete that a GET can reach.

Perfect answer: Look at the access log for GET requests to the delete address, from a crawler’s address or user agent, and find the view that deletes for any method. Restore the rows from the latest backup. Then change the view: a GET shows a confirmation page and changes nothing, and only a POST deletes, with the CSRF token from Chapter 24 and the same permission check as before. Add the test that proves it: a GET leaves the row, a DELETE method is refused with 405, and a POST without the token is refused with 403. Keep crawlers away from private pages with sign-in, not with robots.txt alone.

Behind the scenes:

GET     -> a page that asks first
DELETE  -> 405
POST, no token  -> 403
POST, token     -> the delete

Code proof: a draft, a client that enforces the CSRF check, and three requests, rolled back afterwards:

from datetime import timedelta

from django.db import transaction
from django.test import Client
from django.test.utils import setup_test_environment
from django.utils import timezone

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

setup_test_environment()
sam = User.objects.get(email='sam@example.org')
with transaction.atomic():
    soon = timezone.now() + timedelta(days=7)
    draft = Event.objects.create(
        title='Next week', timezone='Europe/London',
        starts_at=soon, ends_at=soon + timedelta(hours=1),
        location='Online', capacity=20,
    )
    draft.add_organizer(sam)
    url = f'/events/{draft.pk}/delete/'
    web = Client()
    web.force_login(sam)
    print('GET', web.get(url).status_code)
    print('DELETE', web.delete(url).status_code)
    strict = Client(enforce_csrf_checks=True)
    strict.force_login(sam)
    print('POST without token', strict.post(url).status_code)
    kept = Event.objects.filter(pk=draft.pk).exists()
    print('rows kept:', kept)
    transaction.set_rollback(True)
GET 200
Method Not Allowed (DELETE): /events/7/delete/
DELETE 405
POST without token 403
rows kept: True

Common mistakes:

  • Fixing the page and leaving the old address working for any method.
  • Turning off the CSRF check to make the form work.
  • Restoring the data without a test, so the fault returns with the next refactor.

Follow-up the interviewer might ask:

  • “How would you find which rows were deleted?”
  • “What makes a request idempotent, and is a delete idempotent?”

L5 (Lead): The community wants to unpublish events after members registered. What do you advise?

What the interviewer is testing: Can you turn a request into a requirement, name what it breaks, and offer a smaller step that serves the real need?

Flip to check your answerFold answer back
Five numbered steps. The goal is to take an event down after members registered. Unpublishing would hide it from the members who hold places. Cancelling keeps it visible with a tag, which says what happened. Telling members waits for email in Chapters 43 and 44. Advise cancel and copy, and record unpublish as a requirement to decide.
Figure 26.9 — From “unpublish” to a requirement the community can decide.

Perfect answer: Ask what they need. If an event is wrong, cancelling it, with the tag, tells everyone what happened, and copying it gives a corrected draft quickly. Unpublishing would hide the page from the members who hold places, so they would meet “not found” with a registration they cannot see, which is the problem Chapter 26 set out to remove. If they still want it, it is a requirement to decide: what happens to the registrations, who is told, and how it is recorded. Chapter 30’s audit record and Chapters 43 and 44’s email are where that belongs.

Behind the scenes:

cancel() -> status cancelled, registration kept
page     -> 200, with the Cancelled tag, for the member

Code proof: Sai holds a place at a published event, which is then cancelled; she opens its page, rolled back afterwards:

from datetime import timedelta

from django.db import transaction
from django.test import Client
from django.test.utils import setup_test_environment
from django.utils import timezone

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

setup_test_environment()
sai = User.objects.get(email='sai@example.org')
with transaction.atomic():
    soon = timezone.now() + timedelta(days=7)
    event = Event.objects.create(
        title='Meetup', timezone='Europe/London',
        starts_at=soon, ends_at=soon + timedelta(hours=1),
        location='Online', capacity=20, status='published',
    )
    Registration.objects.create(event=event, member=sai)
    event.cancel()
    web = Client()
    web.force_login(sai)
    page = web.get(event.get_absolute_url())
    html = page.content.decode()
    print(page.status_code, 'Cancelled' in html)
    held = event.registrations.active().count()
    print('places still held:', held)
    transaction.set_rollback(True)
200 True
places still held: 1

Common mistakes:

  • Adding an unpublish move without deciding what happens to the registrations.
  • Treating the request as a button, not a requirement.
  • Promising a notification that Otahque cannot send yet.

Follow-up the interviewer might ask:

  • “Who should be allowed to unpublish, and how would you record it?”
  • “What would make you reverse the decision that cancelled is final?”

L6 (Mid-Level): The description migration is applied and a problem appears. How do you roll it back?

What the interviewer is testing: Do you know the command, what it destroys, and when not to use it?

Flip to check your answerFold answer back

Perfect answer: Name the migration you want to go back to, and run uv run python manage.py migrate events 0003: Django unapplies every later migration of the events app, here 0004. Check first with showmigrations events and with migrate --plan, because Django’s documentation warns that dependent migrations in other apps are unapplied too. After the command, showmigrations shows 0004 unticked. For an added column the SQL is a drop, so the descriptions typed since the migration are gone, and sqlmigrate events 0004 --backwards shows that before you run anything. That is acceptable on your own machine. On a shared or deployed database, where rows matter, you do not unapply: you write a new migration that moves forward, and deploy it. Some migrations cannot be reversed at all, and Django then raises an error, as its documentation says.

Behind the scenes:

showmigrations events   -> [X] 0004
migrate events 0003     -> Unapplying events.0004
showmigrations events   -> [ ] 0004
migrate                 -> Applying events.0004

Code proof: the commands from Step 3, on the project:

Operations to perform:
  Target specific migration: 0003_rules, from events
Running migrations:
  Rendering model states... DONE
  Unapplying events.0004_event_description... OK

Common mistakes:

  • Rolling back on a database that holds data you cannot type again.
  • Editing the numbered migration instead of adding a new one.
  • Forgetting that migrate with no arguments applies everything again.

Follow-up the interviewer might ask:

  • “What does migrate events zero do?”
  • “How would you test a migration before you apply it to production?”

L7 (Senior): Before applying the description migration, how do you see the SQL it will run?

What the interviewer is testing: Can you check a migration without running it, read the output, and name the other checks?

Flip to check your answerFold answer back

Perfect answer: Run uv run python manage.py sqlmigrate events 0004. It prints the SQL for that migration without changing the database, and --backwards prints the SQL that unapplies it. It needs a database connection, because it uses it to resolve constraint names, so run it against a copy of the target database. Read the output for what it does to existing rows: here, '' goes into the new column of every row, and on SQLite the table is rebuilt, while on other databases it is one ALTER TABLE ... ADD COLUMN. Two other checks belong beside it: makemigrations --check --dry-run fails when the models and migrations disagree, and migrate --plan lists what a migrate would do. TextField(blank=True) gives existing rows an empty string, never NULL, so the field’s “no data” value is consistent.

Behind the scenes:

sqlmigrate events 0004             -> the SQL, not run
makemigrations --check --dry-run   -> No changes detected
migrate --plan                     -> what migrate would do

Code proof: the SQL from Step 3, forward and back:

BEGIN;
--
-- Add field description to event
--
CREATE TABLE "new__events_event" ("id" integer NOT NULL
    PRIMARY KEY AUTOINCREMENT, "description" text NOT NULL,
    "title" varchar(200) NOT NULL, "starts_at" datetime NOT
    NULL, "ends_at" datetime NOT NULL, "timezone" varchar(64)
    NOT NULL, "location" varchar(200) NOT NULL, "capacity"
    integer unsigned NOT NULL CHECK ("capacity" >= 0),
    "status" varchar(20) NOT NULL, CONSTRAINT
    "event_capacity_gt_0" CHECK ("capacity" > 0), CONSTRAINT
    "event_ends_after_start" CHECK ("ends_at" >
    ("starts_at")), CONSTRAINT "event_status_valid" CHECK
    ("status" IN ('draft', 'published', 'cancelled')));
INSERT INTO "new__events_event" ("id", "title", "starts_at",
    "ends_at", "timezone", "location", "capacity", "status",
    "description") SELECT "id", "title", "starts_at",
    "ends_at", "timezone", "location", "capacity", "status",
    '' FROM "events_event";
DROP TABLE "events_event";
ALTER TABLE "new__events_event" RENAME TO "events_event";
COMMIT;
BEGIN;
--
-- Add field description to event
--
ALTER TABLE "events_event" DROP COLUMN "description";
COMMIT;

Common mistakes:

  • Running migrate first and reading afterwards.
  • Reading the SQL of a different database than the one you deploy to.
  • Assuming a column added with a default is free on a very large table.

Follow-up the interviewer might ask:

  • “How would you add a required column to a large table without locking it?”
  • “What does --backwards print for a migration that cannot be reversed?”
PAGE 006