Sessions (Django)

Django sessions store per-visitor data on the server across requests, keyed by a session id kept in a cookie. They power login state and let you stash data like a shopping cart in request.session, a dict-like object.

Django

HTTP is stateless, so Django uses sessions to remember information between a user's requests. Unlike Flask's default cookie-based session, Django stores the actual data server-side (database, cache, or file) and sends the browser only an opaque session id cookie.

You use it like a dictionary on the request: request.session['cart'] = [...] and request.session.get('cart'). SessionMiddleware loads and saves it automatically, and the authentication system stores the logged-in user's id in the session, which is how login persists.

Configure the backend with SESSION_ENGINE (database is the default; cache is faster), set expiry with set_expiry() or SESSION_COOKIE_AGE, and remember that storing large objects in the session bloats every request's lookup.

Syntax

request.session["key"] = value
request.session.get("key")

Examples

Python

def add_to_cart(request, item_id):
    cart = request.session.get("cart", [])
    cart.append(item_id)
    request.session["cart"] = cart
    return redirect("cart")

Learn it in a lesson

See also

Back to the Dictionary