ContentsClose contents
Pre-release
Chapter 28 · Sessions, cookies, and time zones: Otahque remembers each visitorCHAPTER 28

Complete six-part pre-release for review. Password change and reset are Chapter 29; secure cookies over HTTPS are Chapter 63; tokens for outside programs are Chapter 50. No package and no migration are 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-EIGHT

Sessions, cookies, and time zones: Otahque remembers each visitor

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

Prerequisites: Chapters 15 to 27, including the Chapter 27 project, its 190 passing tests, the profile’s time zone, and the messages Otahque has shown since Chapter 24

What you’ll build: An event list that remembers “Only events with places left” in the session; messages explained, with a close button; a cookie that tells Otahque the browser’s time zone; middleware that shows every page in the viewer’s zone while the admin stays in UTC; event pages that show the venue’s time and the viewer’s; event forms that read typed times in the event’s zone whatever the viewer’s zone; tests of tampering, expiry, and key rotation for signed values; and a written design of what each place holds

Why This Matters

Raj checks the event list most mornings. He only cares about events he can still join, so he wants the list to remember “Only events with places left” between visits, without an account setting and without ticking a box every time. When he saves something, Otahque says so in a message, and he wants to be able to close it.

Sai lives in New York and joins online events run from Delhi. The event pages show Delhi’s time, which she converts in her head and sometimes gets wrong. She wants both: the venue’s time, so she can talk to the organizers, and her own. And when she creates a Delhi event starting at 02:30 on 14 March 2027, Otahque must accept it, even though that night New York’s clocks jump from 02:00 to 03:00.

Sam runs the admin, where Chapter 23 shows every time in UTC with a label that says so. Whatever this chapter changes, his admin must keep saying exactly that.

These requests share one question: what should Otahque remember about a visitor, where, and for how long? The answers are a cookie, a small value the browser keeps and sends back; a session, data Django keeps on the server for one browser; and the database, which keeps what must never be lost. Raj’s filter belongs in the session. Sai’s time zone comes from her profile, or from a cookie her browser writes. Registrations stay in the database, and the chapter proves that nothing in a session can change them.

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

  • explain what a cookie and a session each hold, and read both in the browser and the shell;
  • explain how a message survives a redirect and why it appears once;
  • keep a display preference in the session, and say what must never be kept there;
  • choose a time zone for every request in middleware, and keep one part of the site out of it;
  • show a time in two zones, and read typed times in the right one;
  • show that a signed value can be read but not changed, and say when a token is the wrong tool.

Changing and resetting a password is Chapter 29. Secure cookies over HTTPS are Chapter 63, and a review of session lengths for staff is Chapter 59. Tokens for programs outside Otahque, such as a mobile app, are Chapter 50.

PAGE 001

What You Need to Know

Cookies and sessions

HTTP forgets. Each request arrives on its own, and nothing in it says that the same person sent the one before. A cookie fixes that from the browser’s side: the server’s answer says Set-Cookie: name=value, with some rules attached, and the browser sends name=value back with every later request to that site until the cookie expires.

A cookie can hold the data itself, but then the person can read it and change it, and a cookie holds only about four thousand characters. So Django keeps a session instead: a row in the django_session table holding the data, and a cookie named sessionid holding only the row’s key, 32 random characters. The browser sees the key; the data stays on the server. Signing in, from Chapter 27, is the first thing Otahque keeps there.

Three rules on a cookie matter in this chapter. HttpOnly hides it from the page’s scripts, so a script injected into a page cannot steal it. SameSite=Lax keeps the browser from sending it with a form posted from another site, while still sending it when a person follows a link to Otahque. Max-Age says how long it lives; without one, the cookie is deleted when the browser closes. Table 28.1 lists the cookies Otahque uses by the end of the chapter.

Table 28.1 — Otahque’s cookies
Cookie Holds Lifetime and rules
sessionid The session's key, set by Django Two weeks, or until the browser closes; HttpOnly, SameSite=Lax
csrftoken The CSRF secret from Chapter 24 One year; SameSite=Lax
messages Messages waiting to be shown, signed Until shown; HttpOnly, SameSite=Lax
otahque_tz The browser's time zone, written by site.js One year; SameSite=Lax; scripts may read it

Two weeks is Django’s default, SESSION_COOKIE_AGE, counted from the last time the session changed. Chapter 27’s sign-in page has a Remember me box: a member who leaves it clear gets a sessionid cookie with no Max-Age, which ends when the browser closes. Otahque keeps Django’s defaults, and Step 2 turns them into tests, so that any later change to them is deliberate.

Messages: stored for one request

Chapter 24’s New event page saves the draft, adds “Draft saved.”, and redirects to the event page, which shows the message. The redirect is a second request. The view that added the message has finished before the page that shows it starts, so Django has to keep the message somewhere in between.

That somewhere is Django’s messages framework. By default it stores waiting messages in a cookie named messages, falling back to the session for any that do not fit in it. The cookie is signed, so a person cannot add a message of their own. When the layout’s {% for message in messages %} loop runs, the messages are marked as used, and at the end of that request Django deletes the cookie. Figure 28.1 follows “Draft saved.” through the two requests.

Four numbered cards down the left joined by arrows, and one box on the right. 1, a blue Save card: Sam sends the New event form, a POST, and the view saves the draft. 2, a purple Stored card: messages.success() puts Draft saved. in the signed messages cookie, and the answer is a redirect. 3, a blue Shown card: the browser asks for the event page and sends the cookie back, and the layout shows the message. 4, a green Used up card: Django deletes the cookie, and a reload shows no message. A grey Close box on the right, with an arrow to card 3, says site.js hides the message on this page only, because the server has already used it.
Figure 28.1 — A message across two requests.

So a message is already “dismissed” on the server once it has been shown. Raj’s close button only needs to hide it on the page in front of him, which is a job for a few lines of JavaScript. Each message has a level, such as success or error, and Otahque’s layout styles them differently.

What belongs in a session

A session is the right place for something small that the person can afford to lose: who is signed in, a filter, a step in a form. It is lost when the person signs out, when it expires, or when they switch browser. Everything else, such as events, registrations, and profiles, belongs in the database, where it is shared, kept, and checked by Chapter 21’s rules. Figure 28.2 sorts what Otahque keeps.

Three boxes side by side and a banner. A blue Browser cookies box: sessionid, only a key; messages, signed, until shown; otahque_tz, written by site.js. A purple Session row box: who is signed in, and places_only; may be lost, at sign-out or after two weeks. A green Database box: events, registrations, places left, and profiles; the truth, read on every request. A grey banner below says the session says how to show the list, and the database says what is in it.
Figure 28.2 — What the browser, the session, and the database hold.

Raj’s filter is a display preference: it changes what the list shows him, never what is true. The view reads it from the session and asks the database for the events on every request, so a place cancelled a minute ago brings a full event straight back. Saving to the session also creates a row and sets a cookie, so the view saves the filter only when Raj changes it. A visitor who merely opens the list gets no session at all.

New Concept: a GET that remembers

What problem exists? Chapter 26’s rule says a GET must not change anything. Raj’s filter arrives as /events/?places=1, a GET, and is saved in his session.

What did people do before? Some sites send a filter as a POST with a CSRF token, so it cannot be bookmarked or shared, and the Back button asks to resend a form.

What is it? The rule protects the community’s data. A display preference changes only how this one browser sees the list, and the address shows the choice, so a GET is the right method: it can be bookmarked, shared, and repeated safely.

Why use it? The worst a link from another site can do is tick Raj’s filter. Nothing about events or registrations can change this way, and Step 4’s tests prove it.

Now let’s use it. Step 4 saves the choice when places is in the address, and nothing otherwise.

A time zone for every request

Chapter 24 stores every time in UTC and shows each event in its own zone. Django can also show times in the viewer’s zone. It keeps a current time zone for each request, set with timezone.activate(), and templates and forms use it. Until now, Otahque never set one, so the current zone was always TIME_ZONE = 'UTC'.

Django cannot find out the viewer’s zone by itself: Django’s documentation notes that no request header carries it. Otahque decided on 13 November 2026 to take it from three places, in order: the member’s profile, which Chapter 27 added; the browser, through a cookie; and UTC. The browser knows its zone, and one line of JavaScript, Intl.DateTimeFormat().resolvedOptions().timeZone, returns it, for example Asia/Kolkata. Otahque’s script writes it into a cookie named otahque_tz, and the server reads it on the next request.

New Concept: a cookie the browser wrote

What problem exists? otahque_tz comes from the browser, so anyone can set it to anything, such as Mars/Base or ../../etc/passwd.

What did people do before? Code that trusted such a value passed it straight to the zone library, which raises an error for an unknown name, or reads a file path it should not.

What is it? A value the browser writes is untrusted input, like a form field. The server accepts it only if it is in the list of real zone names, and uses UTC for anything else.

Why use it? A false zone then changes nothing but the times shown to the person who set it. It cannot reach anyone else’s pages or any stored time.

Now let’s use it. Step 6 checks the cookie against available_timezones(), and its tests send the odd values above.

A piece of middleware, code Django runs around every request, finds the zone and activates it. Django’s own documentation shows one that reads the zone from the session; Otahque reads a cookie instead, so a visitor who is not signed in gets no session, and the zone survives signing out. The middleware must run after Django’s AuthenticationMiddleware, because it reads request.user, and it skips the admin, which keeps Chapter 23’s UTC. Figure 28.3 shows the order.

Three numbered cards down the left joined by arrows labelled not set, and two boxes on the right. 1, a green The member’s profile card: Profile.timezone, if the member chose one. 2, a blue The browser’s cookie card: otahque_tz, if it names a real zone. 3, a grey UTC card: when neither is set, or the cookie holds anything else. A purple Every page box says TimezoneMiddleware activates the zone, and templates and forms use it. An orange Admin pages box says they are skipped and always UTC, as Chapter 23 printed.
Figure 28.3 — Choosing the time zone for a request.

The current zone also changes how forms read typed times, and that matters for Chapter 24’s event form. A DateTimeField first reads “2027-03-14 02:30” in the current zone, and refuses a time that does not exist there, or exists twice. Only then does Chapter 24’s in_zone() read the same clock time in the event’s zone. With New York as Sai’s current zone, the first stage refuses a time that is perfectly good in Delhi. So Otahque’s event forms check their fields under UTC, which has no clock changes, and leave the real check to in_zone(), as Figure 28.4 shows.

Four numbered cards down the left joined by arrows, and one red box on the right. 1, a blue Sai types card: 02:30 on 14 March 2027 for a Delhi event, and her pages use New York. 2, a purple Field stage, under UTC card: DateTimeField reads 02:30 UTC; UTC has no clock changes, so nothing is refused here. 3, an orange in_zone() card: reads the same 02:30 in Asia/Kolkata and refuses only its own missing or repeated times. 4, a green Stored card: 21:00 UTC on 13 March. The red Without UtcCleaning box, with an arrow to card 2, says the field reads 02:30 in New York, where it does not exist that night, and refuses it.
Figure 28.4 — A typed time, read in two stages.

On public pages, Otahque shows the venue’s time first and, when the viewer’s clock says something different, the viewer’s too. “Different” means a different offset from UTC at that moment, not a different name: Asia/Calcutta, the old name some browsers still report, and Asia/Kolkata show the same clock, while London and UTC agree in winter and differ in summer.

Signed is not encrypted

Chapter 8 said the secret key “signs” values, so that a change can be detected, and promised to show it with sessions. The messages cookie is such a value. Django’s django.core.signing makes one from any data: the data, written in a form called base64, then a time, then a signature worked out from the data and SECRET_KEY. Anyone can decode the data, because it is not encrypted, but nobody without the key can change it and produce a matching signature. Django’s sessions documentation says the same of its cookie-based sessions: “signed but not encrypted”.

Three more properties follow. A salt separates uses, so a value signed for one purpose fails for another. A TimestampSigner refuses a value older than a max_age you choose. And a signed value works until it expires, however many times it is used, which is called replay; nothing records that it was used. To change the secret key without breaking every signed value at once, put the old key in SECRET_KEY_FALLBACKS: Django checks with it, but never signs with it.

A token is any value a program sends to prove who it is. A JWT, a JSON Web Token, is a signed value of this kind, often recommended in tutorials for signing in. Figure 28.5 compares the three options. Otahque’s own pages come from Otahque’s own site, so a session cookie, with HttpOnly, SameSite, and CSRF protection, is simpler and easier to end; a token is chosen only when a named program outside the site needs one, in Chapter 50.

Three boxes side by side and a banner. A purple Session cookie box: holds a key, and the data stays on the server; signing out deletes it. An orange Signed value box: anyone can read it, and a change is detected; valid until it expires, and cannot be withdrawn one at a time. A green Stored token box: random text looked up in a table, withdrawn by replacing it, Chapter 46. A grey banner says Otahque’s own pages use the session, and a token waits for a named outside client, Chapter 50.
Figure 28.5 — A session, a signed value, and a stored token.

Try it yourself

Que. 1 Raj ticks the filter and closes his browser. He comes back the next day, signed out the whole time. Is the filter still on, and why?

Flip to check your answerFold answer back

Answer. Yes. As a visitor who is not signed in, his session cookie has a Max-Age of two weeks, so it survives closing the browser, and the session row still holds places_only. Had he signed in without Remember me, his session cookie would have ended with the browser, and the filter with it.

Que. 2 Sai’s browser reports Asia/Calcutta. Her profile says America/New_York. Which zone do her pages use, and does the event page for a Delhi event show one time or two?

Flip to check your answerFold answer back

Answer. America/New_York, because the profile comes first. The page shows two times: Delhi’s, and hers. With no profile zone, Asia/Calcutta would be used, and the page would show one time, because Calcutta and Kolkata have the same offset.

PAGE 002

How We Build It

Start from Chapter 27, in the folder containing manage.py, with your own .env, the locked environment, 190 passing tests, every migration applied, the Node.js packages from Chapter 14, and Sam’s superuser password from Chapter 18. No package is added and no migration is made. The new files are accounts/timezones.py, accounts/middleware.py, static/otahque/site.js, events/templates/events/when.html, and docs/design/sessions-and-time-zones.md. The commands are written the same for Windows PowerShell, Git Bash, macOS, Linux, and WSL; the chapter’s checks ran in the first two. Each step with new behaviour writes its tests first and runs them to see them fail. Steps 2 and 5 hold behaviour Django already has, so their tests pass at once.

The Custom Way

Without the session, a remembered filter is often written as a cookie of its own. This illustration is not part of the project:

def event_list(request):
    places_only = request.COOKIES.get('places') == '1'
    response = render(request, 'events/list.html', {
        'places_only': places_only,
    })
    if 'places' in request.GET:
        response.set_cookie('places', request.GET['places'],
                            max_age=60 * 60 * 24 * 365)
    return response

It works, and it starts a habit that grows: every preference becomes another cookie with its own name, lifetime, and rules, each one readable and changeable in the browser, and none of them cleared when the person signs out, so the next person at a shared computer inherits them. The Django Way keeps such values in the one session that Django already protects, ends with sign-out, and expires on a schedule.

The Django Way

Step 1: Check the starting point

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

OK
Destroying test database for alias 'default'...
git status --short
git log --oneline -1
... Add member accounts with django-allauth

Step 2: Look at a session

Start the development server with uv run python manage.py runserver, sign in as Sam at http://127.0.0.1:8000/accounts/login/, and open the browser’s developer tools: in Microsoft Edge and Chrome, press F12 and choose Application, then Cookies. You will see sessionid, csrftoken, and, until the next page, messages. Select sessionid: its value is a key, and the HttpOnly and SameSite columns show Django’s defaults.

To see the server’s side, a practice file signs in a demo member with Django’s test client, prints what each side holds, and undoes its work. Save it as s2_session.py beside manage.py, run it with uv run python manage.py shell -c "exec(open('s2_session.py').read())", and delete it:

from django.contrib.sessions.models import Session
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

setup_test_environment()
PASSWORD = 'a-long-safe-pass-123'
with transaction.atomic():
    User.objects.create_user('demo@example.org', PASSWORD,
                             display_name='Demo')
    web = Client()
    web.post('/accounts/login/', {
        'login': 'demo@example.org', 'password': PASSWORD,
    })
    print('browser holds:', sorted(web.cookies))
    key = web.cookies['sessionid'].value
    print('the key:', len(key), 'random characters')
    row = Session.objects.get(session_key=key)
    print('server holds:', sorted(row.get_decoded()))
    left = row.expire_date - timezone.now()
    days = round(left.total_seconds() / 86400)
    print('the row expires in:', days, 'days')
    transaction.set_rollback(True)
browser holds: ['csrftoken', 'messages', 'sessionid']
the key: 32 random characters
server holds: ['_auth_user_backend', '_auth_user_hash',
    '_auth_user_id', '_session_expiry',
    'account_authentication_methods',
    'account_authentication_methods_user']
the row expires in: 14 days

The browser holds three cookies; the session row holds who signed in, how, and _session_expiry, which allauth sets to 0 when Remember me is clear, meaning “end with the browser”. The row itself still expires in two weeks.

Now hold the rules in place with tests. In events/tests.py, add one import after the Permission import:

from django.contrib.sessions.models import Session

and these tests at the end of the file:

SAI_PASSWORD = 'a-long-safe-pass-123'


class SessionCookieTests(TestCase):
    """What the session cookie keeps, and when it ends."""

    @classmethod
    def setUpTestData(cls):
        cls.sai = User.objects.create_user(
            'sai@example.org', SAI_PASSWORD,
            display_name='Sai',
        )

    def sign_in(self, **extra):
        """Sign Sai in, with any extra form fields."""
        return self.client.post('/accounts/login/', {
            'login': 'sai@example.org',
            'password': SAI_PASSWORD, **extra,
        })

    def test_the_cookie_is_kept_from_scripts(self):
        response = self.sign_in(remember='on')
        cookie = response.cookies['sessionid']
        self.assertTrue(cookie['httponly'])
        self.assertEqual(cookie['samesite'], 'Lax')
        self.assertEqual(cookie['max-age'], 1209600)
        self.assertFalse(cookie['secure'])

    def test_without_remember_me_it_ends_with_the_browser(
            self):
        cookie = self.sign_in().cookies['sessionid']
        self.assertEqual(cookie['max-age'], '')
        self.assertTrue(self.client.session
                        .get_expire_at_browser_close())

    def test_the_row_holds_the_data(self):
        self.sign_in()
        key = self.client.cookies['sessionid'].value
        row = Session.objects.get(session_key=key)
        data = row.get_decoded()
        self.assertEqual(data['_auth_user_id'],
                         str(self.sai.pk))
        self.assertNotIn(SAI_PASSWORD, str(data))
uv run python manage.py test events.tests.SessionCookieTests
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s

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

Step 3: Messages, and a close button

Tests first. They follow “Draft saved.” through Figure 28.1, change the signed cookie, and look for the close button. Add them at the end of events/tests.py:

class MessageTests(TestCase):
    """Messages: shown once, in a signed cookie."""

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

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

    def save_draft(self, **kw):
        """Post the new-event form, with any options."""
        return self.client.post(reverse('events:create'),
                                NEW_EVENT, **kw)

    def test_a_message_is_shown_once(self):
        response = self.save_draft()
        page = self.client.get(response['Location'])
        self.assertContains(page, 'Draft saved.', count=1)
        again = self.client.get(response['Location'])
        self.assertNotContains(again, 'Draft saved.')

    def test_it_waits_in_a_signed_cookie(self):
        response = self.save_draft()
        cookie = response.cookies['messages']
        self.assertIn(':', cookie.value)
        self.assertTrue(cookie['httponly'])
        shown = self.client.get(response['Location'])
        self.assertEqual(
            shown.cookies['messages']['max-age'], 0
        )

    def test_a_changed_cookie_is_ignored(self):
        response = self.save_draft()
        value = response.cookies['messages'].value
        self.client.cookies['messages'] = 'x' + value
        page = self.client.get(response['Location'])
        self.assertNotContains(page, 'Draft saved.')

    def test_a_message_can_be_closed(self):
        page = self.save_draft(follow=True)
        self.assertContains(page, 'alert-success')
        self.assertContains(page, 'data-close')
        self.assertContains(page, 'otahque/site.js')

    def test_an_error_has_the_error_style(self):
        draft = future_draft(self.sam, description='')
        page = self.client.post(
            action_url('publish', draft), follow=True
        )
        self.assertContains(page, 'alert-error')
        self.assertContains(page, 'Add a description.')
uv run python manage.py test events.tests.MessageTests
Found 5 test(s).
Creating test database for alias 'default'...
...
AssertionError: False is not true : Couldn't find 'data-
    close' in the following response
Ran 5 tests in ...s

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

Four of the five pass already, because Django’s messages framework behaves this way: a message is shown once, waits in a signed cookie, and is ignored if the cookie is changed. Only the close button is missing. In templates/base.html, replace the messages block from Chapter 24 with this one, which gives each message a button:

    {% if messages %}
      <div role="status" class="space-y-2">
        {% for message in messages %}
          <div class="alert
            {% if message.level_tag == 'error' %}alert-error
            {% else %}alert-success{% endif %}">
            <span>{{ message }}</span>
            <button type="button" data-close
                    class="btn btn-ghost btn-sm ml-auto">
              Close</button>
          </div>
        {% endfor %}
      </div>
    {% endif %}

The button does nothing yet. Otahque’s first script for every page will do the work. Load it in base.html, just after the stylesheet’s <link>, with defer, so that it runs once the page has been read:

  <script src="{% static 'otahque/site.js' %}"
          defer></script>

Create static/otahque/site.js:

// Otahque's script for every page (Chapter 28).

// Close a message. The server has already used it up;
// this only hides it on the page in front of you.
for (const button of
     document.querySelectorAll('[data-close]')) {
  button.addEventListener('click', () => {
    button.closest('.alert').remove();
  });
}

document.querySelectorAll('[data-close]') finds every element with a data-close attribute, and each button’s click removes the nearest element with the class alert. Rebuild the stylesheet with npm run build, for the button’s classes, and run the tests again:

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

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

Step 4: Remember a filter in the session

Tests first, with one event that has places and one that is full. Add them at the end of events/tests.py:

class PlacesFilterTests(TestCase):
    """The places filter, remembered in the session."""

    @classmethod
    def setUpTestData(cls):
        start = timezone.now() + timedelta(days=7)
        save_event(starts_at=start, capacity=2)
        cls.full = save_event(title='Django workshop',
                              starts_at=start, capacity=1)
        sai = User.objects.create_user(
            'sai@example.org', display_name='Sai'
        )
        Registration.objects.create(event=cls.full,
                                    member=sai)

    def test_the_filter_is_remembered(self):
        self.client.get('/events/?places=1')
        page = self.client.get('/events/')
        self.assertContains(page, 'Python meetup')
        self.assertNotContains(page, 'Django workshop')
        self.assertContains(
            page, 'Showing only events with places left.'
        )

    def test_show_all_clears_it(self):
        self.client.get('/events/?places=1')
        self.client.get('/events/?places=0')
        page = self.client.get('/events/')
        self.assertContains(page, 'Django workshop')
        self.assertFalse(self.client.session['places_only'])

    def test_viewing_alone_saves_no_session(self):
        response = self.client.get('/events/')
        self.assertNotIn('sessionid', response.cookies)
        self.assertFalse(Session.objects.exists())

    def test_places_are_read_from_the_database(self):
        self.client.get('/events/?places=1')
        self.assertNotContains(self.client.get('/events/'),
                               'Django workshop')
        self.full.registrations.update(
            status=Registration.Status.CANCELLED,
            cancelled_at=timezone.now(),
        )
        page = self.client.get('/events/')
        self.assertContains(page, 'Django workshop')
uv run python manage.py test events.tests.PlacesFilterTests
Found 4 test(s).
Creating test database for alias 'default'...
...
KeyError: 'places_only'
AssertionError: 1 != 0 :'Django workshop' unexpectedly found
    in the following response
Ran 4 tests in ...s

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

In events/views.py, replace event_list():

def event_list(request):
    """List published events; remember the places filter."""
    choice = request.GET.get('places')
    if choice in ('0', '1'):
        # Saved only when the visitor changes the filter.
        request.session['places_only'] = choice == '1'
    places_only = request.session.get('places_only', False)
    now = timezone.now()
    events = Event.objects.published().with_places()
    upcoming = events.upcoming(now)
    if places_only:
        upcoming = upcoming.filter(places_left__gt=0)
    return render(request, 'events/list.html', {
        'upcoming': upcoming,
        'past': events.past(now),
        'now': now,
        'places_only': places_only,
    })

request.session behaves like a dictionary. The view writes to it only when places is 0 or 1 in the address, so an ordinary visit saves nothing, and reads it with .get(), so a visitor without a session gets False. The filter applies to upcoming events, using Chapter 22’s places_left, which the database counts afresh on every request. Past events are listed as before.

The form goes in events/templates/events/list.html, just after <h1>Events</h1>:

  <form method="get"
        class="flex flex-wrap items-center gap-3">
    <input type="hidden" name="places" value="0">
    <label class="flex items-center gap-2">
      <input type="checkbox" name="places" value="1"
             class="checkbox"
             {% if places_only %}checked{% endif %}>
      Only events with places left
    </label>
    <button type="submit" class="btn btn-sm">Filter</button>
  </form>
  {% if places_only %}
    <p class="filter-note text-sm">
      Showing only events with places left.
      <a href="?places=0">Show all</a></p>
  {% endif %}

A checkbox that is not ticked sends nothing at all, so the form also sends a hidden places=0. When the box is ticked, the browser sends both, places=0&places=1, and Django’s request.GET.get() returns the last value for a repeated name, which is 1. Rebuild the stylesheet with npm run build, and run the tests:

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

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

Common Error: modifying a value inside the session

request.session['filters']['places'] = True changes a dictionary inside the session, and Django does not notice: it saves a session only when a key of the session itself is set or deleted. Set the whole value again, as Step 4 does, or set request.session.modified = True after changing something inside it.

Step 5: Sign-out and expiry

Signing out flushes the session: Django deletes the row and the cookie, so Raj’s filter goes with them. The zone cookie of the next step is separate, and stays. An expired session is the same as none. These tests pass at once, because Django already behaves this way; they keep it so. Add them at the end of events/tests.py:

class SessionEndTests(TestCase):
    """What signing out and expiry forget."""

    @classmethod
    def setUpTestData(cls):
        start = timezone.now() + timedelta(days=7)
        full = save_event(title='Django workshop',
                          starts_at=start, capacity=1)
        cls.sai = User.objects.create_user(
            'sai@example.org', display_name='Sai'
        )
        Registration.objects.create(event=full,
                                    member=cls.sai)

    def test_sign_out_clears_the_filter_not_the_zone(self):
        self.client.force_login(self.sai)
        self.client.cookies['otahque_tz'] = 'Asia/Kolkata'
        self.client.get('/events/?places=1')
        self.client.post('/accounts/logout/')
        page = self.client.get('/events/')
        self.assertContains(page, 'Django workshop')
        self.assertEqual(
            self.client.cookies['otahque_tz'].value,
            'Asia/Kolkata',
        )

    def test_an_expired_session_is_forgotten(self):
        self.client.get('/events/?places=1')
        session = self.client.session
        session.set_expiry(-1)
        session.save()
        page = self.client.get('/events/')
        self.assertContains(page, 'Django workshop')
uv run python manage.py test events.tests.SessionEndTests
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s

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

set_expiry(-1) makes the session one second past its end, as if two weeks had gone by. The next request finds no row it may use, and starts again with an empty session.

Step 6: The browser’s time zone

The zone tests go in accounts/tests.py, and need a few more imports. Put these at the very top of the file, above the allauth imports; Steps 7 and 10 use the ones this step does not:

import base64
import time
from datetime import UTC, datetime
from unittest import mock
from zoneinfo import ZoneInfo

and this one after from .models import Profile, User:

from .timezones import (
    COOKIE, resolve_timezone, to_user_time,
)

Then the tests, at the end. request_with() builds a request as the middleware will see it, with a cookie and a member:

def request_with(cookie=None, user=None):
    """Build a request as the middleware sees it."""
    request = RequestFactory().get('/')
    if cookie is not None:
        request.COOKIES[COOKIE] = cookie
    request.user = user or AnonymousUser()
    return request


class BrowserZoneTests(TestCase):
    """Which zone a viewer gets: profile, cookie, UTC."""

    def test_a_real_zone_is_used(self):
        zone = resolve_timezone(request_with('Asia/Kolkata'))
        self.assertEqual(zone, ZoneInfo('Asia/Kolkata'))

    def test_an_alias_is_a_real_zone(self):
        request = request_with('Asia/Calcutta')
        zone = resolve_timezone(request)
        self.assertEqual(str(zone), 'Asia/Calcutta')

    def test_anything_else_means_utc(self):
        for value in (None, '', 'Mars/Base',
                      '../../etc/passwd'):
            with self.subTest(value=value):
                zone = resolve_timezone(request_with(value))
                self.assertEqual(zone, ZoneInfo('UTC'))

    def test_the_profile_zone_comes_first(self):
        sai = User.objects.create_user(
            'sai@example.org', display_name='Sai'
        )
        Profile.objects.create(user=sai,
                               timezone='Europe/London')
        request = request_with('Asia/Kolkata', sai)
        self.assertEqual(resolve_timezone(request),
                         ZoneInfo('Europe/London'))

    def test_to_user_time(self):
        moment = datetime(2026, 12, 3, 12, 30, tzinfo=UTC)
        request = request_with('Asia/Kolkata')
        local = to_user_time(moment, request)
        self.assertEqual(f'{local:%H:%M %Z}', '18:00 IST')
uv run python manage.py test accounts.tests.BrowserZoneTests
Found 1 test(s).
Creating test database for alias 'default'...
...
ImportError: Failed to import test module: tests
ModuleNotFoundError: No module named 'accounts.timezones'
Ran 1 test in ...s

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

The module does not exist yet. Create accounts/timezones.py:

"""Which time zone to show a viewer, and times in it."""
from zoneinfo import ZoneInfo, available_timezones

from django.utils import timezone

from .models import Profile

# The cookie site.js writes with the browser's time zone.
COOKIE = 'otahque_tz'
KNOWN = frozenset(available_timezones())
UTC = ZoneInfo('UTC')


def resolve_timezone(request):
    """Return the zone to show times in.

    The member's profile, then the browser's cookie,
    then UTC.
    """
    user = request.user
    if user.is_authenticated:
        saved = Profile.objects.filter(
            user=user
        ).values_list('timezone', flat=True).first()
        if saved:
            return ZoneInfo(saved)
    name = request.COOKIES.get(COOKIE, '')
    if name in KNOWN:
        return ZoneInfo(name)
    return UTC


def to_user_time(value, request):
    """value, an aware datetime, in the viewer's zone."""
    zone = resolve_timezone(request)
    return timezone.localtime(value, zone)

KNOWN is the set of real zone names, built once when the module is loaded, because building it reads hundreds of files. The profile is read with .filter(...).values_list(...).first(), which returns None instead of making a profile, so a page view never writes to the database. to_user_time() is for Python code that needs a time in the viewer’s zone, such as a message; templates get the zone from the middleware of Step 7.

Now the script writes the cookie. In static/otahque/site.js, add this block after the first comment line, above the close-button block:

// Tell the server this browser's time zone. The cookie is
// a display preference: the server checks it is a real
// zone name, and a member's profile zone comes first.
const browserZone = Intl.DateTimeFormat()
  .resolvedOptions().timeZone;
if (browserZone) {
  document.cookie = 'otahque_tz=' + browserZone
    + '; path=/; max-age=31536000; samesite=lax';
}

path=/ sends the cookie to every page, max-age=31536000 is one year in seconds, and samesite=lax is the same rule as the session’s. A script cannot set HttpOnly, and does not need to: the value is not a secret.

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

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

Step 7: One zone for every request

Tests first. They check where the middleware sits, that Sam’s profile zone reaches his pages, and that the admin still reads typed times as UTC. In accounts/tests.py, add from django.conf import settings above from django.contrib.auth import get_user_model, and replace from events.tests import admin_url with:

from events.models import Event
from events.tests import admin_url, event_form, save_event

Then the tests, at the end:

class TimezoneMiddlewareTests(TestCase):
    """Pages in the viewer's zone; the admin in UTC."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = User.objects.create_superuser(
            'sam@example.org', PASSWORD, display_name='Sam'
        )
        Profile.objects.create(user=cls.sam,
                               timezone='Asia/Kolkata')

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

    def test_it_runs_after_authentication(self):
        names = settings.MIDDLEWARE
        ours = 'accounts.middleware.TimezoneMiddleware'
        auth = ('django.contrib.auth.middleware.'
                'AuthenticationMiddleware')
        self.assertGreater(names.index(ours),
                           names.index(auth))

    def test_pages_use_the_profile_zone(self):
        page = self.client.get('/accounts/profile/')
        self.assertRegex(page.content.decode(),
                         r'shown to you in\s+Asia/Kolkata')

    def test_the_admin_stays_in_utc(self):
        event = save_event(
            starts_at=datetime(2026, 12, 3, 9, tzinfo=UTC),
            timezone='Asia/Kolkata',
        )
        url = admin_url(Event, 'change', event.pk)
        self.client.post(url, event_form(
            event, starts_at_1='15:00', ends_at_1='17:00',
        ))
        event.refresh_from_db()
        typed = datetime(2026, 12, 3, 15, tzinfo=UTC)
        self.assertEqual(event.starts_at, typed)
uv run python manage.py test accounts -k TimezoneMiddleware
Found 3 test(s).
Creating test database for alias 'default'...
...
ValueError: list.index(x): x not in list
Ran 3 tests in ...s

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

The admin test already passes, because no zone is active yet; it is there to keep it so. The middleware is a class that Django creates once, with the next step in the chain as get_response, and calls once for each request. Create accounts/middleware.py:

"""Middleware that shows pages in the viewer's zone."""
from django.urls import reverse
from django.utils import timezone

from .timezones import resolve_timezone


class TimezoneMiddleware:
    """Show every page in the viewer's zone.

    The admin is the exception: it stays in UTC (Chapter 23).
    """

    def __init__(self, get_response):
        """Keep the next handler in the chain."""
        self.get_response = get_response

    def __call__(self, request):
        """Turn on the viewer's zone for this request."""
        if request.path.startswith(reverse('admin:index')):
            timezone.deactivate()
        else:
            timezone.activate(resolve_timezone(request))
        return self.get_response(request)

reverse('admin:index') gives the admin’s address, which Chapter 23 reads from DJANGO_ADMIN_URL, so the check follows it if it changes. timezone.deactivate() returns to TIME_ZONE, UTC. In config/settings.py, add the middleware to MIDDLEWARE, on the line after AuthenticationMiddleware:

    'accounts.middleware.TimezoneMiddleware',

Last, tell members which zone they see. In accounts/templates/accounts/profile.html, add {% load tz %} after the extends line, and these lines after the first paragraph:

  {% get_current_timezone as zone %}
  <p class="text-sm">Event times are shown to you in
     {{ zone }}: your profile's zone if you chose one,
     otherwise your browser's, otherwise UTC.</p>
uv run python manage.py test accounts -k TimezoneMiddleware
uv run python manage.py test
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s

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

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

Common Error: the middleware above AuthenticationMiddleware

Middleware runs in the order of the list. Put TimezoneMiddleware above AuthenticationMiddleware and request.user does not exist yet when it runs, so every page fails with AttributeError: 'WSGIRequest' object has no attribute 'user'. Move the line below AuthenticationMiddleware, as above.

Common Error: an admin in the viewer’s zone

Without the admin check, the admin’s forms read typed times in Sam’s zone, while their help text still says “In UTC”. Sam types 15:00 meaning UTC, and Django stores 15:00 in Asia/Kolkata, which is 09:30 UTC. Nothing warns him; only Step 7’s test sees it, failing with datetime(2026, 12, 3, 9, 30, ...) where it expected 15:00. Keep the admin:index check in the middleware.

Step 8: Typed times in the event’s zone

Since Step 7, the New event page reads typed times in the viewer’s zone before Chapter 24’s in_zone() sees them, as Figure 28.4 shows. Tests first. In events/tests.py, add from zoneinfo import ZoneInfo after from pathlib import Path, and change from .forms import EventForm to from .forms import CopyForm, EventForm. Then add the tests at the end. timezone.override() makes a zone current for the length of a with block, as the middleware does for a request:

NEW_YORK = ZoneInfo('America/New_York')


class ViewerZoneFormTests(TestCase):
    """Typed times belong to the event's zone.

    That holds whatever zone the viewer's page uses.
    """

    def test_a_new_york_viewer_creates_a_delhi_event(self):
        with timezone.override(NEW_YORK):
            form = new_event_form(
                timezone='Asia/Kolkata',
                starts_at='2027-03-14T02:30',
                ends_at='2027-03-14T04:00',
            )
            self.assertTrue(form.is_valid(), form.errors)
        self.assertEqual(
            in_utc(form, 'starts_at'),
            datetime(2027, 3, 13, 21, 0, tzinfo=UTC),
        )

    def test_the_event_zone_still_refuses_its_own_gap(self):
        with timezone.override(NEW_YORK):
            form = new_event_form(
                timezone='Europe/London',
                starts_at='2027-03-28T01:30',
                ends_at='2027-03-28T03:00',
            )
            self.assertFormError(
                form, 'starts_at',
                '01:30 does not exist in Europe/London '
                'that day: the clocks go forward.',
            )

    def test_the_copy_form_too(self):
        event = save_event(timezone='Asia/Kolkata')
        with timezone.override(NEW_YORK):
            form = CopyForm(
                {'starts_at': '2027-11-07T01:30'},
                event=event,
            )
            self.assertTrue(form.is_valid(), form.errors)

    def test_the_new_event_page_with_a_new_york_cookie(self):
        self.client.force_login(editor())
        self.client.cookies['otahque_tz'] = str(NEW_YORK)
        self.client.post(reverse('events:create'), {
            **NEW_EVENT, 'timezone': 'Asia/Kolkata',
            'starts_at': '2027-03-14T02:30',
            'ends_at': '2027-03-14T04:00',
        })
        self.assertTrue(Event.objects.exists())
uv run python manage.py test events.tests.ViewerZoneFormTests
Found 4 test(s).
Creating test database for alias 'default'...
...
AssertionError: False is not true
Ran 4 tests in ...s

FAILED (failures=3)
Destroying test database for alias 'default'...

Three fail. The output above is shortened; in yours, each failure ends with Django’s own message, such as 2027-03-14 02:30:00 couldn’t be interpreted in time zone America/New_York; it may be ambiguous or it may not exist. The London test passes: 01:30 on 28 March 2027 does not exist in London, and Otahque’s message says so, as it should. In events/forms.py, add this class just before EventForm:

class UtcCleaning:
    """Clean typed times under UTC.

    UTC has no clock changes; in_zone() then reads them in
    the event's zone, whatever zone the viewer's page uses.
    """

    def full_clean(self):
        """Run every check with UTC as the current zone."""
        with timezone.override(UTC):
            super().full_clean()

and put it first in both forms’ parents, so that its full_clean() runs around theirs:

class EventForm(UtcCleaning, forms.ModelForm):
class CopyForm(UtcCleaning, forms.Form):

full_clean() is the method is_valid() calls to run every check, from Chapter 25’s validation lifecycle. Inside timezone.override(UTC), the field stage reads typed text in UTC, where no time is missing or doubled, and in_zone() then reads the same clock time in the event’s zone, as it always has.

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

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

Step 9: The venue’s time and yours

Tests first, with a Delhi clinic seen from four browsers. Add them at the end of events/tests.py:

class BothTimesTests(TestCase):
    """When an event shows the viewer's time as well."""

    @classmethod
    def setUpTestData(cls):
        cls.clinic = save_event(
            title='Delhi clinic', timezone='Asia/Kolkata',
            starts_at=datetime(2026, 12, 3, 12, 30,
                               tzinfo=UTC),
        )

    def page(self, zone):
        """Open the clinic's page for a viewer in zone."""
        self.client.cookies['otahque_tz'] = zone
        url = self.clinic.get_absolute_url()
        return self.client.get(url)

    def test_the_venue_zone_shows_one_time(self):
        page = self.page('Asia/Kolkata')
        self.assertContains(
            page, 'Thursday 3 December 2026, 18:00 IST'
        )
        self.assertNotContains(page, 'Your time')

    def test_another_zone_shows_both(self):
        page = self.page('America/New_York')
        self.assertContains(
            page, 'Thursday 3 December 2026, 18:00 IST'
        )
        self.assertContains(
            page,
            'Your time: Thursday 3 December 2026, 07:30 EST',
        )

    def test_an_alias_shows_one_time(self):
        page = self.page('Asia/Calcutta')
        self.assertNotContains(page, 'Your time')

    def test_summer_time_counts(self):
        july = save_event(
            starts_at=datetime(2027, 7, 1, 17, tzinfo=UTC)
        )
        winter = save_event(
            starts_at=datetime(2027, 1, 14, 18, tzinfo=UTC)
        )
        utc = ZoneInfo('UTC')
        self.assertTrue(july.differs_for(utc))
        self.assertFalse(winter.differs_for(utc))
uv run python manage.py test events.tests.BothTimesTests
Found 4 test(s).
Creating test database for alias 'default'...
...
AttributeError: 'Event' object has no attribute 'differs_for'
Ran 4 tests in ...s

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

The rule goes on the model. In events/models.py, change the first line to from zoneinfo import ZoneInfo, available_timezones, and add this method to Event, before can_be_edited_by:

    def differs_for(self, zone=None):
        """Return whether zone shows another start time.

        It is compared with the venue's zone; by default,
        zone is the viewer's.
        """
        zone = zone or timezone.get_current_timezone()
        start = self.starts_at
        venue = start.astimezone(ZoneInfo(self.timezone))
        return start.astimezone(zone).utcoffset() != (
            venue.utcoffset()
        )

With no argument, it compares with the current zone, so a template can call it. utcoffset() is the clock’s distance from UTC at that moment, such as +5:30 in Delhi, so two names for the same clock compare equal.

Three pages show times: the list, the event page, and My events. One small template shows a time for all three. Create events/templates/events/when.html:

{% load tz %}
{% with moment=at|default:event.starts_at %}
{% with shape=format|default:"D j M Y, H:i T" %}
  {% timezone event.timezone %}
    {{ moment|date:shape }}
  {% endtimezone %}
  {% if event.differs_for %}
    <span class="your-time block text-sm">
      Your time: {{ moment|date:shape }}</span>
  {% endif %}
{% endwith %}
{% endwith %}

It shows at, or the event’s start when at is not given, in the format given, or in the list’s short format. {% timezone event.timezone %} shows the venue’s time, as Chapter 19 did; the line below it, outside that block, is in the zone the middleware activated. Now use it. In events/templates/events/list.html, replace the {% timezone %} block in the row with:

          <span class="text-sm">
            {% include "events/when.html" %}
          </span>

In events/templates/events/detail.html, replace the {% timezone %} block with:

    {% with format="l j F Y, H:i T" %}
    <p>From {% include "events/when.html" %}</p>
    <p>Until
      {% include "events/when.html" with at=event.ends_at %}
    </p>
    {% endwith %}

and in events/templates/events/manage.html, replace its {% timezone %} block with:

        <p class="text-sm">
          {% include "events/when.html" %}</p>

The three templates no longer use the timezone tag themselves, so delete the {% load tz %} line from each. Rebuild the stylesheet with npm run build, and run the tests:

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

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

Step 10: Signing, the design, and the commit

See what a signed value is with a practice file. Save it as s10_signing.py, run it like the one in Step 2, and delete it:

import base64

from django.core import signing

SALT = 'otahque.demo'
value = signing.dumps({'places_only': True}, salt=SALT)
data, stamp, signature = value.split(':')
print('parts:', len(data), len(stamp), len(signature))
padded = data + '=' * (-len(data) % 4)
print('anyone can read:', base64.urlsafe_b64decode(padded))
print('loads():', signing.loads(value, salt=SALT))
changed = value.replace(data, data[:-1] + '1', 1)
cases = [('one letter changed', changed, SALT),
         ('another salt', value, 'other')]
for label, text, salt in cases:
    try:
        signing.loads(text, salt=salt)
    except signing.BadSignature as error:
        print(f'{label}:', type(error).__name__)
parts: 27 6 43
anyone can read: b'{"places_only":true}'
loads(): {'places_only': True}
one letter changed: BadSignature
another salt: BadSignature

The value has three parts, separated by colons: the data, a time, and the signature. The data decodes without any key. Change one letter, or use another salt, and loads() refuses. The tests add expiry and key rotation, which need a clock and a second key. In accounts/tests.py, change from django.core import mail to from django.core import mail, signing, and add at the end:

SALT = 'otahque.demo'


class SigningTests(SimpleTestCase):
    """Signed values: read, refused if changed, expire."""

    def test_a_signed_value_can_be_read(self):
        value = signing.dumps({'places_only': True},
                              salt=SALT)
        data = value.split(':')[0]
        data += '=' * (-len(data) % 4)
        self.assertEqual(base64.urlsafe_b64decode(data),
                         b'{"places_only":true}')

    def test_a_changed_value_is_refused(self):
        value = signing.dumps({'places_only': True},
                              salt=SALT)
        signature = value.split(':', 1)[1]
        forged = base64.urlsafe_b64encode(
            b'{"places_only":false}'
        ).decode().rstrip('=')
        with self.assertRaises(signing.BadSignature):
            signing.loads(f'{forged}:{signature}', salt=SALT)

    def test_an_old_value_expires(self):
        two_minutes_ago = time.time() - 120
        with mock.patch('time.time',
                        return_value=two_minutes_ago):
            value = signing.dumps('x', salt=SALT)
        with self.assertRaises(signing.SignatureExpired):
            signing.loads(value, salt=SALT, max_age=60)
        self.assertEqual(
            signing.loads(value, salt=SALT, max_age=600), 'x'
        )

    def test_a_new_key_needs_the_old_one_as_fallback(self):
        value = signing.dumps('x', salt=SALT)
        old = settings.SECRET_KEY
        new = 'a-new-secret-key-' + 'n' * 40
        with override_settings(SECRET_KEY=new):
            with self.assertRaises(signing.BadSignature):
                signing.loads(value, salt=SALT)
        with override_settings(SECRET_KEY=new,
                               SECRET_KEY_FALLBACKS=[old]):
            self.assertEqual(signing.loads(value, salt=SALT),
                             'x')
uv run python manage.py test accounts.tests.SigningTests
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s

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

mock.patch('time.time', ...) makes Python’s clock say two minutes ago while the value is signed, so it is two minutes old when it is checked. override_settings() changes a setting for one block, here the secret key. These tests describe Django’s behaviour, so they pass at once; the chapter’s interview questions build on them.

Record the design in docs/design/sessions-and-time-zones.md:

# Sessions, cookies, and time zones: low-level design

Status: Drafted in Chapter 28, for review. Not approved.

## What each place holds

- sessionid cookie: the session key only. Two weeks;
  until the browser closes for a member who signs in
  without ticking Remember me. HttpOnly, SameSite=Lax.
- django_session row: who is signed in, and
  places_only. Two weeks from the last change.
- messages cookie: signed messages, until shown.
- otahque_tz cookie: the browser's zone, one year.
- Database: events, registrations, and profiles.

Registrations and places left are always read from the
database. The session holds only what may be lost.

## The places filter

- /events/?places=1 saves places_only = True in the
  session; ?places=0 saves False. A plain visit saves
  nothing, so no session is made for a visitor.
- Signing out flushes the session, and the filter with
  it. An expired session is the same as none.

## Time zones

- site.js writes otahque_tz on every page (path /,
  max-age one year, SameSite=Lax; not HttpOnly, not
  signed: the browser writes it).
- accounts.timezones.resolve_timezone(request): the
  profile's zone, then the cookie if it names a real
  zone, then UTC. to_user_time() converts one value.
- accounts.middleware.TimezoneMiddleware, after
  AuthenticationMiddleware, activates that zone; admin
  pages are skipped and stay in UTC (Chapter 23).
- events/when.html shows the venue's time, and "Your
  time" when Event.differs_for() finds another UTC
  offset at the start.
- EventForm and CopyForm clean under UTC (UtcCleaning);
  in_zone() reads typed times in the event's zone.

## Signing

Signed values (the messages cookie, signing.dumps())
can be read but not changed; TimestampSigner adds an
expiry; SECRET_KEY_FALLBACKS keeps old values valid
during a key change. Nothing is encrypted.

## Open

- Secure cookie settings: Chapter 63.
- Session timeouts and SameSite review: Chapter 59.
- Tokens for outside clients: Chapter 50.
- The zone cookie in a consent notice: a later chapter.

Check, test, and commit:

uv run python manage.py makemigrations --check --dry-run
uv run python manage.py test
No changes detected
Found 224 test(s).
Creating test database for alias 'default'...
...
Ran 224 tests in ...s

OK
Destroying test database for alias 'default'...
git add .
git status --short
git commit -m "Remember visitors: sessions and time zones"
A  accounts/middleware.py
M  accounts/templates/accounts/profile.html
M  accounts/tests.py
A  accounts/timezones.py
M  config/settings.py
A  docs/design/sessions-and-time-zones.md
M  events/forms.py
M  events/models.py
M  events/templates/events/detail.html
M  events/templates/events/list.html
M  events/templates/events/manage.html
A  events/templates/events/when.html
M  events/tests.py
M  events/views.py
M  static/otahque/site.css
A  static/otahque/site.js
M  templates/base.html

Common Error: two scripts declaring the same name

Scripts loaded with ordinary <script> tags share one set of top-level names. Chapter 24’s event-zone.js declares const zone; if site.js declared const zone too, the New event page would stop the second script with a SyntaxError, Identifier 'zone' has already been declared, in the browser’s console, and the form would no longer choose Sam’s time zone for him. That is why site.js uses browserZone. Give each top-level name in a shared script a name no other script uses.

Table 28.2 lists what to do when a step does not go as described.

Table 28.2 — When a step goes wrong
Symptom Likely cause Recovery
AttributeError: no attribute 'user' TimezoneMiddleware above AuthenticationMiddleware Move it to the line after AuthenticationMiddleware
Admin times shifted by hours The admin check missing from the middleware Restore the admin:index check from Step 7
couldn't be interpreted in time zone America/New_York UtcCleaning missing from a form Put UtcCleaning first in the form's parents, as in Step 8
The filter is forgotten at once The view does not write to request.session Compare event_list with Step 4
No "Your time" line anywhere Script blocked, or the cookie not yet sent Reload once; check site.js loads in the developer tools
The close button does nothing site.js not loaded, or a name declared twice Check the console in the developer tools
PAGE 003

Verify Your Work

Work through Table 28.3 from the folder that holds manage.py. For the browser rows, start the development server, and use a private window so that no earlier cookie is sent.

Table 28.3 — Verification checklist for Chapter 28
Check Command or action Expected result
Starting point uv run python manage.py test Found 190 test(s); OK
Tests fail first Each step's new tests, before the code FAILED, or an import error
Tests pass uv run python manage.py test Found 224 test(s); OK
No migration waiting makemigrations --check --dry-run No changes detected
Zone cookie Open /events/; developer tools, Application, Cookies otahque_tz with your zone; no sessionid yet
Both times Reload /events/ The venue's time, and "Your time" where your clock differs
Filter remembered Tick Only events with places left, Filter, then open Events again The box still ticked; "Showing only events with places left."
Session cookie Developer tools, after the filter sessionid, HttpOnly, SameSite Lax
Message Sign in, save your profile Profile saved., with a Close button that hides it
Message used up Reload the profile No message
Your zone The profile page "Event times are shown to you in" and your zone
Sign-out Sign out, then open Events The filter is off; otahque_tz is still there
Admin /admin/events/event/ Start (UTC), as in Chapter 23
Phone width Device toolbar, 390 px No sideways scroll
Committed git status --short No output
Not verified macOS, Linux, WSL; Firefox, Safari Readers on those systems

The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 27 checkpoint, with each listing applied in the order printed. The browser rows were walked through in Microsoft Edge at 390 px with the browser set to Asia/Kolkata, and at 1280 px set to America/New_York. Edge wrote India’s zone into otahque_tz as Asia/Calcutta, the older name, and the pages showed one time for the Delhi workshop, as Step 9 intends.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 3 What does the sessionid cookie hold, and where is the rest of the session?

Flip to check your answerFold answer back

Answer. Only the session’s key, 32 random characters. The data, such as who is signed in and places_only, is in a row of the django_session table, found by that key.

Que. 4 Why does the event_list view write to the session only when places is in the address?

Flip to check your answerFold answer back

Answer. Writing creates a session row and sets a cookie. Writing only when Raj changes the filter means an ordinary visit saves nothing, so visitors who never use the filter get no session.

Que. 5 Raj signs out. What happens to his filter and to otahque_tz, and why?

Flip to check your answerFold answer back

Answer. The filter is gone, because signing out flushes the session, row and cookie. otahque_tz stays: it is a cookie of its own, written by the browser, and holds nothing about Raj.

Que. 6 Someone sets otahque_tz to Mars/Base. What do they see, and what can they change for anyone else?

Flip to check your answerFold answer back

Answer. Times in UTC, because the server accepts only real zone names. Nothing for anyone else: the cookie affects only how times are shown to the browser that sent it.

Que. 7 Why does UtcCleaning put the forms’ checks under UTC, not under the event’s zone?

Flip to check your answerFold answer back

Answer. UTC has no clock changes, so Django’s field stage never refuses a typed time, and in_zone() keeps the one real check in the event’s zone, with Otahque’s own messages. Reading under the event’s zone would check the same thing twice, with two different messages.

Mini-Challenge

Que. 8 Predict what Sam sees after saving his profile: on the page the redirect leads to, and after he reloads it. Is the message waiting in a cookie in between? Then check with l2_messages.py below, run with uv run python manage.py shell -c "exec(open('l2_messages.py').read())".

Flip to check your answerFold answer back

Answer. The message waits in the messages cookie on the redirect, appears on the next page, and is gone after a reload, because showing it used it up. The file undoes its work, so your rows are unchanged:

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

from accounts.models import User

setup_test_environment()
with transaction.atomic():
    demo = User.objects.create_user(
        'demo@example.org', display_name='Demo'
    )
    web = Client()
    web.force_login(demo)
    sent = web.post('/accounts/profile/', {
        'display_name': 'Demo K', 'timezone': '',
    })
    print('waiting in a cookie:', 'messages' in sent.cookies)
    for visit in ('first page', 'after a reload'):
        page = web.get(sent['Location']).content.decode()
        print(f'{visit}:', 'Profile saved.' in page)
    transaction.set_rollback(True)
waiting in a cookie: True
first page: True
after a reload: False

What We Learned

  • A cookie is a value the browser sends back; a session keeps the data on the server and gives the browser only its key.
  • Django’s session cookie is HttpOnly and SameSite=Lax, and lasts two weeks, or until the browser closes when Remember me is clear.
  • A message waits in a signed cookie for one request and is used up when shown; a close button only hides it.
  • A session holds what may be lost; registrations and places are always read from the database.
  • A value the browser writes is untrusted input: check it against a known list.
  • Middleware can choose the time zone for every request; its place in the list matters, and part of the site can be left out.
  • Forms read typed times in the current zone, so Otahque checks its event forms under UTC and reads times in the event’s zone.
  • Two zones show the same time when their offsets from UTC are equal at that moment.
  • Signed values can be read but not changed; they expire only if you ask, can be replayed, and survive a key change only with a fallback.

Key terms

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

Table 28.4 — Key terms from Chapter 28
Term Meaning
Cookie A value the browser keeps and sends back with each request to the site.
Session Data Django keeps on the server for one browser, found by the key in the sessionid cookie.
HttpOnly A cookie rule that hides the cookie from the page's scripts.
SameSite=Lax A cookie rule: not sent with forms posted from other sites.
Messages framework Django's store for one-request messages, such as "Draft saved."
Display preference A choice about how one person sees a page, never what is true.
Middleware Code Django runs around every request, in the order of MIDDLEWARE.
Current time zone The zone Django uses for one request's templates and forms.
UTC offset How far a clock is from UTC at a given moment, such as +5:30.
Signature A value worked out from data and the secret key, so a change is detected.
Salt Text that separates the uses of signing.
Replay Using a valid signed value again, which signing alone cannot stop.

Readiness checkpoint: you are ready for Chapter 29 when all 224 tests pass, makemigrations --check --dry-run prints No changes detected, the event list remembers the filter until you sign out, a message appears once and can be closed, event pages show your own time where it differs, the admin still shows UTC, and the commit is made.

Git Commit

Your Chapter 28 work was committed in Step 10, with the message “Remember visitors: sessions and time zones”. It holds the filter in event_list() and its form, the messages block and site.js, accounts/timezones.py and accounts/middleware.py with their place in MIDDLEWARE, the profile’s zone line, UtcCleaning in the event forms, Event.differs_for() and when.html in three pages, the rebuilt stylesheet, the design note, and thirty-four new tests.

PAGE 005

Test Your Knowledge: Interview Questions

These five questions rehearse the chapter at interview level, from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead: attempt them now, and return after Chapters 29 and 50. They are extension questions, not a gate to the next chapter.

L1 (Junior): What is the difference between a cookie and a session?

What the interviewer is testing: Do you know which side holds what, and why that matters for safety?

Flip to check your answerFold answer back

Perfect answer: A cookie is a value the browser keeps and sends back with every request to the site, so the person can read it and change it. A session is data the server keeps for one browser; the browser holds only a cookie with the session’s random key. Django stores sessions in the database by default and marks the cookie HttpOnly and SameSite=Lax. So a session suits data the person must not change, such as who is signed in, and the server can end it at any time by deleting the row.

Behind the scenes:

GET /events/?places=1  -> session row saved: places_only
answer                 -> Set-Cookie: sessionid=<key>
next request           -> sessionid sent; row read again

Code proof: a visitor ticks the filter; what each side holds, rolled back afterwards:

from django.contrib.sessions.models import Session
from django.db import transaction
from django.test import Client
from django.test.utils import setup_test_environment

setup_test_environment()
with transaction.atomic():
    web = Client()
    web.get('/events/?places=1')
    print('browser holds:', sorted(web.cookies))
    key = web.cookies['sessionid'].value
    row = Session.objects.get(session_key=key)
    print('server holds:', row.get_decoded())
    transaction.set_rollback(True)
browser holds: ['sessionid']
server holds: {'places_only': True}

Common mistakes:

  • Thinking the session’s data is in the cookie.
  • Storing data in a plain cookie that the person could change.
  • Forgetting that every saved session is a database row.

Follow-up the interviewer might ask:

  • “When would you store sessions in the cache instead of the database?”
  • “What does HttpOnly protect against, and what does it not?”

L2 (Mid-Level): Sam saves his profile, then reloads the page. Predict what each page shows.

What the interviewer is testing: Can you trace a message across a redirect and say why it appears once?

Flip to check your answerFold answer back
Four numbered steps. Sam saves his profile, and the view adds Profile saved. and redirects. The message waits in the signed messages cookie. The next page shows it, and Django marks it used. A reload shows nothing, because the cookie was deleted.
Figure 28.6 — A message, then a reload.

Perfect answer: The page after the redirect shows “Profile saved.”; the reload shows no message. The view adds the message and answers with a redirect, so Django stores it in the signed messages cookie. The next request sends the cookie back, the layout’s loop shows the message and marks it used, and Django deletes the cookie with that response. The reload has nothing to show.

Behind the scenes:

POST /accounts/profile/  -> 302; Set-Cookie: messages=...
GET  /accounts/profile/  -> shown; cookie deleted
GET  (reload)            -> no message

Code proof: the Mini-Challenge’s l2_messages.py:

waiting in a cookie: True
first page: True
after a reload: False

Common mistakes:

  • Rendering the page after a POST instead of redirecting, so a reload sends the form again.
  • Leaving out the messages loop on a page, so a message waits and appears on a later one.
  • Storing a message in the session by hand and never deleting it.

Follow-up the interviewer might ask:

  • “Where would a message go if it were too large for the cookie?”
  • “How would you show a message that must stay until the member reads it?”

L3 (Senior): Defend reading registrations from the database, never from the session.

What the interviewer is testing: Can you say what may be lost, what must be true, and prove the boundary with a test?

Flip to check your answerFold answer back
Five numbered steps. The goal is that places shown always match the registrations. A session holds only what may be lost. Places left are counted from the database on every request. The test cancels a place, and the full event comes back. The session only says how to show the list.
Figure 28.7 — Why places come from the database.

Perfect answer: A session belongs to one browser and may be lost at any time: at sign-out, at expiry, or on another device. Registrations are shared and must be true for everyone, with Chapter 21’s rules checking them. If a page trusted a copy in the session, a place cancelled by someone else would not show, and a lost session would hide a member’s place. So the session keeps only Raj’s choice to filter; the database counts places on every request. The test cancels a place behind the session’s back, and the full event reappears in the filtered list.

Behind the scenes:

session      -> places_only = True
database     -> workshop full, then a place cancelled
next request -> places counted again; workshop shown

Code proof: the Step 4 test test_places_are_read_from_the_database, run on its own:

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

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

Common mistakes:

  • Caching a member’s registrations in the session to save a query.
  • Treating a value in the session as checked because the person cannot edit it.
  • Testing only the happy path, never a change made by someone else.

Follow-up the interviewer might ask:

  • “When would caching places be acceptable, and how would you keep it correct?”
  • “What belongs in a session in a multi-step form?”

L4 (Staff): Sai’s 02:30 Delhi event is refused with a message naming America/New_York. Diagnose.

What the interviewer is testing: Can you trace a refusal to the stage that made it, and fix the cause rather than the symptom?

Flip to check your answerFold answer back
Five numbered steps. Sai’s 02:30 Delhi event is refused, naming America/New_York. The message is Django’s field stage, read in the active zone. Her pages use New York, where 02:30 on 14 March does not exist. Clean under UTC, and in_zone() reads the time in the event’s zone. Add a test with the viewer’s zone active.
Figure 28.8 — Diagnosing a refused time.

Perfect answer: The message names New York, not Delhi, so it is not Otahque’s in_zone() check; it is Django’s DateTimeField, which reads typed text in the current zone. Since the middleware activates each viewer’s zone, Sai’s form is read in New York first, where 02:30 on 14 March 2027 is skipped by the clock change. The fix is not to switch the middleware off: clean the form under UTC, which has no clock changes, and let in_zone() read the time in the event’s zone. A test with New York active proves it, beside one showing that London still refuses its own missing hour.

Behind the scenes:

field, in New York  -> 02:30 does not exist: refused
field, under UTC    -> accepted as text
in_zone(), Delhi    -> 02:30 IST = 21:00 UTC, saved

Code proof: a plain field and EventForm, with New York active:

from zoneinfo import ZoneInfo

from django import forms
from django.utils import timezone

from events.forms import EventForm


class Typed(forms.Form):
    starts_at = forms.DateTimeField()


delhi = {'title': 'Delhi clinic', 'location': 'Online',
         'timezone': 'Asia/Kolkata', 'capacity': '20',
         'starts_at': '2027-03-14T02:30',
         'ends_at': '2027-03-14T04:00'}
with timezone.override(ZoneInfo('America/New_York')):
    plain = Typed({'starts_at': delhi['starts_at']})
    print('a plain field:', plain.is_valid())
    print(plain.errors['starts_at'][0])
    print('EventForm:', EventForm(delhi).is_valid())
a plain field: False
2027-03-14 02:30:00 couldn’t be interpreted in time zone
    America/New_York; it may be ambiguous or it may not
    exist.
EventForm: True

Common mistakes:

  • Turning the middleware off for every form page.
  • Reading times under the event’s zone, so the same gap is checked twice.
  • Testing forms only with the default zone, UTC, which never shows the fault.

Follow-up the interviewer might ask:

  • “Which other forms in a project would be affected by activating a zone?”
  • “How would you show a member a time that falls in their own clock change?”

L5 (Lead): A developer proposes JWTs instead of sessions for Otahque’s pages. What do you advise?

What the interviewer is testing: Can you compare the two on what matters, ending a sign-in, theft, and effort, and keep a decision open for the right case?

Flip to check your answerFold answer back
Five numbered steps. The goal is sign-in that is easy to end and hard to steal. A session is an HttpOnly cookie with a key, and sign-out deletes the data. A JWT is a signed value, readable, and valid until it expires. Otahque’s pages come from its own site, so cookies and CSRF already work. Use tokens only for a named outside client, Chapter 50.
Figure 28.9 — Sessions or tokens for Otahque’s pages.

Perfect answer: Keep sessions for Otahque’s own pages. A JWT is a signed value: anyone holding it can read it, and it works until it expires, so signing out, a password change, or a stolen token cannot end it without a list of withdrawn tokens kept on the server, which is a session again in another form. A session cookie is HttpOnly, so page scripts cannot read it, the server ends it by deleting the row, and Django already pairs it with CSRF protection. The pages and the server share one site, so nothing needs a token. When a named outside client appears, such as a mobile app, choose its authentication then, in Chapter 50.

Behind the scenes:

session        -> row deleted: the key is worthless
signed token   -> still valid until it expires
stored token   -> valid until its row is deleted

Code proof: a session and a signed token, after the same sign-out:

from django.contrib.sessions.backends.db import SessionStore
from django.core import signing

session = SessionStore()
session['member'] = 7
session.save()
key = session.session_key
token = signing.dumps({'member': 7}, salt='otahque.demo')

session.flush()  # what signing out does
print('session after sign-out:',
      dict(SessionStore(session_key=key).items()))
print('signed token after sign-out:',
      signing.loads(token, salt='otahque.demo'))
session after sign-out: {}
signed token after sign-out: {'member': 7}

Common mistakes:

  • Choosing JWTs because they are “stateless”, then adding a list of withdrawn tokens.
  • Keeping a token where page scripts can read it.
  • Deciding the API’s authentication before there is an API client.

Follow-up the interviewer might ask:

  • “What would change for a mobile app that uses the same accounts?”
  • “How does Chapter 46’s check-in token differ from a signed value?”
PAGE 006