StaffCoder
Django
DjangoDjango 5.2Python 3.13
18 modules · 72 challengesSign up
Module 14 · Sessions & Messages

Session Preferences And Expiry

mediumDjango SessionsInput Validation—No data yet

Problem statement

In this Django project, implement the reading preferences the catalog keeps forgetting. A theme is picked and the next page renders light again, a page size is chosen and twelve rows come back anyway, and nothing is validated, so theme=chartreuse would be as good as any other value. Every session also inherits the two-week global default in the read-only project/settings.py, which is not the site's policy: a visitor is forgotten after thirty minutes, or the moment they close the browser if that is what they asked for.

Requirements

Implement:

  • browse, preferences and clear_preferences in app/views.py

The following files are already implemented and provided: app/models.py, app/prefs.py, app/urls.py, both templates and project/settings.py. Listing holds a title and orders itself by it, and the fixtures are twelve listings, so 5, 10 and 25 rows apart are three visibly different pages. The routes are given: / (home) and /accounts/login/ (login) are complete, /browse/ (browse) is the catalog page, /preferences/ (preferences) renders the form on GET and saves on POST, and /preferences/clear/ (clear-preferences) resets on POST. The templates are read-only: app/templates/app/browse.html renders listings as <li class="listing"> rows and nothing else, app/templates/app/preferences.html pre-selects whatever the visitor has already chosen, and both pages put the theme on the <body> element as class="theme-<value>". Both pages read exactly three context names: theme, page_size and forget_on_close. app/prefs.py holds every value this question is graded against and is imported rather than retyped: the session keys THEME_KEY (prefs:theme), PAGE_SIZE_KEY (prefs:page_size) and FORGET_KEY (prefs:forget_on_close); the allowed values THEMES (light, dark, contrast) and PAGE_SIZES (the integers 5, 10, 25); the defaults DEFAULT_THEME (light), DEFAULT_PAGE_SIZE (10) and DEFAULT_FORGET_ON_CLOSE (False); and SESSION_AGE, which is 1800 seconds. project/settings.py is read-only and keeps Django's own global defaults, SESSION_COOKIE_AGE = 1209600 and SESSION_EXPIRE_AT_BROWSER_CLOSE = False; they are deliberately not the policy, because the policy is per visitor.

1. One reader for the three values

  • One reader turns a session into theme, page_size and forget_on_close, supplying prefs.DEFAULT_THEME, prefs.DEFAULT_PAGE_SIZE and prefs.DEFAULT_FORGET_ON_CLOSE for whatever is not stored.
  • Both pages render from it, so a visitor who never chose and a visitor who cleared get the same page.
  • The default belongs in the reader, never written into the session. A visitor who has chosen nothing has none of the three keys stored at all, or else "never chose" and "chose the default" become indistinguishable and a clear cannot put things back as they were.

2. GET /browse/ and GET /preferences/

  • browse renders app/browse.html with theme, page_size and forget_on_close, and with listings already cut to the page size: five chosen means five <li class="listing"> rows on the page, not twelve rows and a note.
  • The preferences GET renders app/preferences.html with the same three names, so each control shows the current choice.
  • page_size reaches the template as an integer, because the form template compares it against integers.

3. POST /preferences/

  • theme is stored under prefs.THEME_KEY only when it is one of prefs.THEMES, and page_size under prefs.PAGE_SIZE_KEY only when it is one of prefs.PAGE_SIZES, as an integer.
  • Anything else is ignored: an unknown theme, page_size=loads, page_size=7, a field that did not arrive. Nothing is stored under that key, and an earlier valid choice stays standing.
  • forget_on_close is stored under prefs.FORGET_KEY as True when the checkbox arrived and False when it did not, so every save decides the toggle one way or the other.
  • Then redirect to browse.

4. The expiry policy, per visitor

  • Every page you render leaves the session carrying the policy: prefs.SESSION_AGE seconds from this request, or browser-close for a visitor whose forget_on_close is true.
  • Browser-close means the sessionid cookie goes out with no Max-Age and no Expires at all. The policy age means a cookie carrying both, with the age prefs.SESSION_AGE seconds from now.
  • The policy is stamped once this visitor's choice is known: on a rendered page, and again after a save or a clear changes the answer. The toggle is a preference like the others, so it keeps applying to later pages until it is changed or cleared.
  • The tests read this the way a browser would: get_expiry_age() on the session for the age, and the Max-Age and Expires attributes of the sessionid cookie for the browser-close behaviour. Nothing is graded by reading a setting back, and the age must not be the global SESSION_COOKIE_AGE.

5. POST /preferences/clear/

  • Removes the three preference keys and nothing else, then redirects to browse.
  • The defaults render again on the next page, and because the default is not "forget me", the policy age applies again.
  • A visitor who was signed in is still signed in afterwards, with _auth_user_id still in the session.

Notes

  • set_expiry has three distinct calls and the last two are easy to confuse: a number of seconds is a lifetime from now, 0 is no stored lifetime at all so the browser drops the cookie when it quits, and None forgets the per-session value and hands the visitor back to SESSION_COOKIE_AGE.
  • An unticked checkbox does not arrive in request.POST at all, so an absent forget_on_close is False rather than "no opinion". An absent or rejected theme or page_size means "leave what was there".
  • request.POST is whatever arrived: check membership in the allowed set before storing, and store nothing when the value is not in it, so the reader's default covers the gap. int(request.POST["page_size"]) on page_size=loads is a 500.
  • Only app/views.py changes, and every key, allowed value, default and the expiry age comes from app/prefs.py.
  • Clear the preference keys one by one. Do not flush, cycle or replace the session: the login lives in it too.
  • Do not reach for the cache framework, a model, a cookie of your own or a querystring, and do not try to make SESSION_COOKIE_AGE do the per-visitor job.

More in Sessions & Messages

See the module
Session Shopping CartAnonymous visitors lose their cart on every page change because nothing persists between requests. Keep the cart in the session, mutate it correctly on add, update and remove with the session flagged as modified, and work the totals out server-side from the price list.—No data yetmediumFlash Message FeedbackEvery action on the reading list works and then redirects, so the page comes back looking identical whether the save landed, the row was deleted, or the title arrived empty. Queue the defined message at the defined level from each action and render the queue once in the base template, styled by level and empty-handed on the next request.—No data yetmediumGuest Checkout FlowA guest checkout walks from the cart to the details to the confirmation, but nothing carries between the steps, no step says what just happened, and an abandoned flow sits in the session store for a fortnight. Build the three steps on session state with a message at every transition, keep the entries through back-navigation, and clear only the flow's own keys on completion under the documented expiry policy.—No data yetmedium

We use cookies that are necessary to run Staffcoder, and optional analytics cookies to see which pages get used. Analytics stays off unless you accept. Read our Cookie Policy.