Sessions
Store per-visitor data across requests with the session framework.
Syntax
request.session["key"] = valueThe session framework stores data tied to a visitor between requests, keyed by a cookie. Read and write it like a dictionary through request.session. Django's auth system is built on top of it.
Session data is stored server-side by default (in the database), so only an opaque id lives in the cookie.
Example
def add_to_cart(request, product_id):
cart = request.session.get("cart", [])
cart.append(product_id)
request.session["cart"] = cart # save
return redirect("cart")
def view_cart(request):
cart = request.session.get("cart", [])
return render(request, "cart.html", {"cart": cart})When to use it
- A developer stores a shopping cart in the user's session so items persist across page navigations without a database lookup.
- A developer reads request.session to retrieve a previously stored preference like the user's selected language.
- A team sets SESSION_COOKIE_AGE in settings to expire sessions after 30 minutes of inactivity for security.
More examples
Write and read session data
Stores and retrieves a cart dictionary from the session so it persists across requests.
def add_to_cart(request, product_id):
cart = request.session.get("cart", {})
cart[str(product_id)] = cart.get(str(product_id), 0) + 1
request.session["cart"] = cart
return redirect("cart")
def cart_view(request):
cart = request.session.get("cart", {})
return render(request, "cart.html", {"cart": cart})Delete a session key
Removes a specific key from the session; ignores KeyError if the key doesn't exist.
def clear_cart(request):
try:
del request.session["cart"]
except KeyError:
pass
return redirect("cart")Configure session expiry
Sets a 30-minute rolling session timeout and restricts the cookie to HTTPS connections.
# settings.py
SESSION_COOKIE_AGE = 1800 # 30 minutes
SESSION_SAVE_EVERY_REQUEST = True # reset timer on each request
SESSION_COOKIE_SECURE = True # HTTPS only
Discussion