← Back to Django, page 3

django-0058 · Easy fresher

What are sessions in Django, how do they differ from cookies, and where is session data stored?

A cookie stores a small value in the browser. A session keeps data on the server and sends the browser only a random session ID in a cookie. Django's request.session behaves like a dict, defaults to the database backend, and can instead use cache, cached_db, files or signed cookies. Never store secrets in plain cookies, and treat session data as server-trusted but expiry and fixation as risks.

Full answer

HTTP is stateless, so sites need a way to remember a visitor.

Cookies: response.set_cookie("theme", "dark", max_age=86400, httponly=True, secure=True, samesite="Lax"). The browser sends them on every matching request, and the user can read and change them. Use get_signed_cookie / set_signed_cookie to detect tampering.

Sessions: the browser holds only sessionid (random, unguessable). The data lives on the server and is loaded via request.session["cart"]. SessionMiddleware provides it, and login uses it to remember request.user.

Backends (SESSION_ENGINE):

  • django.contrib.sessions.backends.db (default): table django_session, survives restarts, extra query per request that uses the session. Clear old rows with manage.py clearsessions.
  • cache: fast, but data is lost if the cache is flushed.
  • cached_db: write-through, a good default for busy sites.
  • signed_cookies: no server storage, but data lives in the cookie, is readable (signed, not encrypted), size-limited, and cannot be revoked.

Useful settings: SESSION_COOKIE_AGE, SESSION_COOKIE_SECURE, SESSION_COOKIE_HTTPONLY (default True), SESSION_COOKIE_SAMESITE, SESSION_EXPIRE_AT_BROWSER_CLOSE.

Security: login() rotates the session key to prevent fixation; keep sessions small and JSON-serialisable (the default serializer is JSON); changing a password invalidates the user's other sessions through the session auth hash; request.session.flush() on logout.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    ROOT_URLCONF=__name__,
    MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"],
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "django.contrib.sessions", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.contrib.sessions.models import Session
from django.db import connection
from django.http import JsonResponse
from django.test import Client
from django.urls import path

with connection.schema_editor() as editor:
    editor.create_model(Session)


def add_to_cart(request, item):
    cart = request.session.get("cart", [])
    cart.append(item)
    request.session["cart"] = cart                      # assignment marks the session as modified
    response = JsonResponse({"cart": cart})
    response.set_cookie("theme", "dark", max_age=3600, httponly=True, samesite="Lax")
    return response


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

c = Client()
print(c.get("/add/notebook/").json())
print(c.get("/add/pen/").json())
print(sorted(c.cookies.keys()))
print(c.cookies["sessionid"]["httponly"], c.cookies["theme"]["samesite"])
print(Session.objects.count(), "session row in the database")
print(list(Session.objects.get().get_decoded().items()))
other = Client()
print(other.get("/add/ruler/").json())                  # a new visitor starts with a new session

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. The sessions table is created with the schema editor; a real project runs migrate. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): {'cart': ['notebook']} {'cart': ['notebook', 'pen']} ['sessionid', 'theme'] True Lax 1 session row in the database [('cart', ['notebook', 'pen'])] {'cart': ['ruler']}

Key points

  • Cookies live in the browser; sessions hold data on the server
  • Only a random session ID is sent in the cookie
  • Backends: db, cache, cached_db, files, signed_cookies
  • Set Secure, HttpOnly and SameSite flags
  • login() rotates the key; flush() on logout

Common mistakes

  • Storing passwords or tokens in plain cookies
  • Using signed_cookies for sensitive or large data
  • Forgetting clearsessions, so django_session grows forever
  • Mutating a nested object in the session without reassigning it

Follow-ups

  • Why does Django not encrypt signed cookie sessions?
  • How would you log a user out of all devices?
  • When is a JWT better than a session?

Tips

  • Contrast browser-held and server-held data
  • Name two backends
  • Mention cookie flags