Django by Example: Session Data Storage
Sessions allow you to store arbitrary data about the current site visitor across requests. This code example shows how Django handles the details of generating session IDs and storing the data securely.
Code
def set_session_data(request):
# 1. Setting data
# Sessions act like a dictionary
request.session['fav_color'] = 'blue'
request.session['cart_items'] = [1, 5, 22]
# 2. Setting expiry
# Expire in 5 minutes (300 seconds)
request.session.set_expiry(300)
# Expire when browser closes
# request.session.set_expiry(0)
return HttpResponse("Session data set")
def get_session_data(request):
# 3. Getting data
# Use .get() to avoid KeyErrors if data isn't there
color = request.session.get('fav_color', 'red')
cart = request.session.get('cart_items', [])
return HttpResponse(f"Color: {color}, Cart: {cart}")
def delete_session_data(request):
# 4. Deleting specific keys
if 'fav_color' in request.session:
del request.session['fav_color']Explanation
HTTP is a stateless protocol, meaning each request is independent. To remember a user (e.g., "User ID 42 is logged in"), Django uses sessions. A session is a temporary storage area on the server, linked to a specific browser via a cookie containing a unique Session ID.
Django's session framework abstracts the details of cookie handling and data storage. You can treat request.session like a standard Python dictionary. By default, session data is stored in the database (django_session table), but you can configure it to use a cache (Redis/Memcached), files, or signed cookies for better performance.
Security Note: Django's sessions are secure by default. The session ID cookie is set with HttpOnly (JavaScript cannot read it) and SameSite='Lax' (prevents CSRF). If you store sensitive data, ensure you're using HTTPS so the cookie is encrypted in transit.
Code Breakdown
request.session['fav_color']. Sessions behave like standard Python dictionaries. Changes are automatically saved at the end of the request.set_expiry(300). Sets the session to expire in 5 minutes. If 0 is passed, the session expires when the browser closes.request.session.get(). Always use .get() to retrieve session data to avoid KeyError if the session has expired or the key doesn't exist.
