TExcelTAD
Home › Django › Django Sessions & Messages

Django Sessions & Messages

HTTP is stateless: each request arrives on its own, and the server has no built-in memory of who sent the previous one. Yet sites remember your shopping cart, your language and whether you're logged in. Django's session framework provides that memory, and the messages framework — built on top of sessions — shows one-time notifications such as "Your profile was saved."

How sessions work

  1. On the first request that stores something, Django creates a session and sends the browser a cookie named sessionid.
  2. The browser sends the cookie back with every later request.
  3. SessionMiddleware uses it to load the session data into request.session, a dictionary-like object.

Where the data itself lives depends on SESSION_ENGINE:

Engine Data stored in Notes
django.contrib.sessions.backends.db (default) the django_session table needs django.contrib.sessions + migrate
…backends.cache / …backends.cached_db cache (+ database) fast
…backends.file files on the server
…backends.signed_cookies the cookie itself, signed with SECRET_KEY no server storage; users can read (not change) the data

Using request.session

request.session behaves like a dictionary. Values must be JSON-serialisable (strings, numbers, lists, dicts…). The test client keeps cookies between requests just like a browser, so we can watch a visit counter grow:

python · try it yourself
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(
    SECRET_KEY="demo-secret-key", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
    INSTALLED_APPS=["django.contrib.sessions"],
    MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.core.management import call_command
from django.http import HttpResponse
from django.urls import path
from django.test import Client

call_command("migrate", verbosity=0)          # creates the django_session table

def counter(request):
    visits = request.session.get("visits", 0) + 1
    request.session["visits"] = visits
    return HttpResponse(f"Visits so far: {visits}")

def reset(request):
    request.session.flush()                     # delete data + cookie
    return HttpResponse("Session cleared.")

urls.urlpatterns = [path("", counter), path("reset/", reset)]

alice, bob = Client(), Client()                 # two different browsers
for _ in range(3):
    print("alice:", alice.get("/").content.decode())
print("bob:  ", bob.get("/").content.decode())
print("cookie name:", list(alice.cookies.keys()))
print(alice.get("/reset/").content.decode())
print("alice:", alice.get("/").content.decode())
alice: Visits so far: 1
alice: Visits so far: 2
alice: Visits so far: 3
bob:   Visits so far: 1
cookie name: ['sessionid']
Session cleared.
alice: Visits so far: 1

Each client has its own cookie and therefore its own session.

A shopping cart in the session

Sessions are ideal for data that belongs to a visitor but isn't worth a database table yet — like a cart before checkout. Here we use the signed-cookie engine, which needs no table at all:

python · try it yourself
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(
    SECRET_KEY="demo-secret-key", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
    SESSION_ENGINE="django.contrib.sessions.backends.signed_cookies",
    MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"],
)
django.setup()
from django.http import JsonResponse
from django.urls import path
from django.test import Client

PRICES = {"tea": 4, "cake": 6, "juice": 3}

def add_to_cart(request, item):
    cart = request.session.get("cart", {})
    cart[item] = cart.get(item, 0) + 1
    request.session["cart"] = cart            # reassign so Django notices the change
    return JsonResponse(cart)

def checkout(request):
    cart = request.session.pop("cart", {})
    total = sum(PRICES[item] * qty for item, qty in cart.items())
    return JsonResponse({"items": cart, "total": total})

urls.urlpatterns = [path("add/<str:item>/", add_to_cart), path("checkout/", checkout)]

c = Client()
for item in ["tea", "cake", "tea"]:
    print(c.get(f"/add/{item}/").json())
print(c.get("/checkout/").json())
print(c.get("/checkout/").json())
{'tea': 1}
{'tea': 1, 'cake': 1}
{'tea': 2, 'cake': 1}
{'items': {'tea': 2, 'cake': 1}, 'total': 14}
{'items': {}, 'total': 0}

Note: Django saves the session only when it knows it was modified — i.e. when you assign a key or delete one. Mutating a nested object in place (request.session["cart"]["tea"] += 1) isn't detected; reassign the value or set request.session.modified = True.

The messages framework

Messages are short notifications stored for exactly one future request — typically: perform an action, add a message, redirect, and the next page displays it. Reading the messages consumes them.

Function Level / CSS tag
messages.debug(request, "…") debug (hidden by default)
messages.info(request, "…") info
messages.success(request, "…") success
messages.warning(request, "…") warning
messages.error(request, "…") error
python · try it yourself
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(
    SECRET_KEY="demo-secret-key", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
    INSTALLED_APPS=["django.contrib.messages"],
    SESSION_ENGINE="django.contrib.sessions.backends.signed_cookies",
    MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware",
                "django.contrib.messages.middleware.MessageMiddleware"],
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates",
                "OPTIONS": {
                    "context_processors": ["django.contrib.messages.context_processors.messages"],
                    "loaders": [("django.template.loaders.locmem.Loader", {
                        "home.html": "{% for m in messages %}[{{ m.tags }}] {{ m }}\n{% empty %}(no messages)\n{% endfor %}<h1>Home</h1>",
                    })]}}],
)
django.setup()
from django.contrib import messages
from django.shortcuts import render, redirect
from django.urls import path
from django.test import Client

def save_profile(request):
    messages.success(request, "Profile saved.")
    messages.warning(request, "Your email is not verified yet.")
    return redirect("/")

def home(request):
    return render(request, "home.html")

urls.urlpatterns = [path("", home), path("profile/save/", save_profile)]

c = Client()
r = c.post("/profile/save/", follow=True)
print(r.content.decode())
print("--- reload ---")
print(c.get("/").content.decode())
[success] Profile saved.
[warning] Your email is not verified yet.
<h1>Home</h1>
--- reload ---
(no messages)
<h1>Home</h1>

After being displayed once, the messages were gone. A typical base template shows them in one place for the whole site:

html
{% if messages %}
<ul class="messages">
  {% for message in messages %}
  <li class="alert alert-{{ message.tags }}">{{ message }}</li>
  {% endfor %}
</ul>
{% endif %}

Session settings worth knowing

Setting Default Meaning
SESSION_COOKIE_AGE 1209600 (2 weeks) lifetime in seconds
SESSION_EXPIRE_AT_BROWSER_CLOSE False end session when the browser closes
SESSION_COOKIE_SECURE False only send over HTTPS — set True in production
SESSION_COOKIE_HTTPONLY True hide the cookie from JavaScript

Test yourself

How does Django know which session belongs to a request?

  1. By the IP address
  2. By a sessionid cookie sent by the browser
  3. By the URL
  4. By the User-Agent

Why might request.session["cart"]["tea"] += 1 not be saved?

  1. Sessions are read-only
  2. Django doesn't detect in-place changes to nested objects
  3. Integers can't be stored
  4. The cart key is reserved

How long does a message added with messages.success() live?

  1. Forever
  2. Until it is displayed (iterated) once
  3. One hour
  4. Until logout