🎓 A1Learner
🔍
0 of 50 lessons completed

Django Sessions

A session keeps values between requests. Django holds the values on the server for one reader.

Turn on sessions

These settings lines add the sessions app and its middleware. The middleware runs on every request.

INSTALLED_APPS = ["django.contrib.sessions"]
MIDDLEWARE = ["django.contrib.sessions.middleware.SessionMiddleware"]

Count the visits

The view takes the count from the session, adds one, and saves it back.

def count(request):
    request.session["visits"] = request.session.get("visits", 0) + 1
    return HttpResponse("Visits: " + str(request.session["visits"]))

Visit twice

The same test client comes back twice. The count climbs, because the session holds it.

client = Client()
print(client.get("/count").content.decode())
print(client.get("/count").content.decode())

Read the count from the session

The test client keeps the session after the visits. The count reads back as 2.

print(client.session["visits"])

Example

import django
from django.conf import settings

settings.configure(
    DEBUG=True,
    SECRET_KEY="key",
    ROOT_URLCONF=__name__,
    ALLOWED_HOSTS=["*"],
    INSTALLED_APPS=[
        "django.contrib.contenttypes",
        "django.contrib.auth",
        "django.contrib.sessions",
    ],
    MIDDLEWARE=[
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.contrib.auth.middleware.AuthenticationMiddleware",
    ],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True}],
    LOGIN_URL="/login/",
)
django.setup()

from django.core.management import call_command
from django.http import HttpResponse
from django.urls import path
from django.test import Client


def count(request):
    request.session["visits"] = request.session.get("visits", 0) + 1
    return HttpResponse("Visits: " + str(request.session["visits"]))


urlpatterns = [path("count", count)]

call_command("migrate", verbosity=0)

client = Client()
print(client.get("/count").content.decode())
print(client.get("/count").content.decode())
print(client.session["visits"])

Key points

  • request.session is a dict that lasts across requests.
  • request.session["visits"] stores a value under visits.
  • The browser keeps a small key that names the session.
  • Sessions need the sessions app and its middleware.
  • Middleware is a layer that runs on every request.
  • A session keeps values for one reader across requests.

In this example, the setup lines configure Django. The program runs migrations first. The count view reads the stored visit count and adds one. The test client visits /count twice with one client, so the key keeps the count between visits. The prints show Visits: 1, then Visits: 2, then the stored count of 2.

Note

A session holds small values, never large files.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Where does Django keep session values between requests?