Django Sessions – A Complete Guide

Last updated 1 month, 2 weeks ago | 133 views 75     5

Tags:- Python Django

In any dynamic web application, maintaining user state across multiple requests is essential. This is where sessions come in. Django provides a powerful and secure session framework that simplifies session management while offering flexibility and customization.


What Are Sessions?

Sessions allow you to store information for a particular user across requests. Unlike cookies that store data on the client-side, Django sessions store data on the server-side and use a cookie only to store a session key that identifies the user’s session.


⚙️ How Django Sessions Work

  1. A user accesses the site.

  2. Django checks for a sessionid cookie in the request.

  3. If it doesn't exist, a new session is created.

  4. Django saves data to the server, keyed by a unique session ID.

  5. The session ID is stored in the client browser as a cookie.


Enabling Sessions in Django

Django sessions are enabled by default, but here’s how to make sure everything is set up:

1. Add to INSTALLED_APPS (already included by default)

'django.contrib.sessions',

2. Enable Middleware in settings.py:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',  # ✅ Required
    'django.middleware.common.CommonMiddleware',
    ...
]

3. Run Migrations (for DB backend)

python manage.py migrate

This creates a django_session table to store session data.


Using Sessions in Views

✅ Set Session Data

def set_session(request):
    request.session['user_name'] = 'JohnDoe'
    request.session['is_logged_in'] = True
    return HttpResponse("Session data has been set.")

✅ Get Session Data

def get_session(request):
    name = request.session.get('user_name', 'Guest')
    return HttpResponse(f"Hello, {name}")

✅ Delete a Session Key

def delete_session_key(request):
    try:
        del request.session['user_name']
    except KeyError:
        pass
    return HttpResponse("Session key deleted.")

✅ Clear All Session Data

def clear_session(request):
    request.session.flush()  # Deletes all data and regenerates the session key
    return HttpResponse("Session cleared.")

Configuring Sessions in settings.py

You can customize how sessions behave using Django’s settings.

Setting Description Default
SESSION_ENGINE Backend used to store session data 'django.contrib.sessions.backends.db'
SESSION_COOKIE_NAME Cookie name for the session ID 'sessionid'
SESSION_COOKIE_AGE Lifetime of cookie in seconds 1209600 (2 weeks)
SESSION_EXPIRE_AT_BROWSER_CLOSE Expire session when browser closes False
SESSION_SAVE_EVERY_REQUEST Save session on every request False
SESSION_COOKIE_SECURE Send cookie only over HTTPS False
SESSION_COOKIE_HTTPONLY Prevent JavaScript access True
SESSION_COOKIE_SAMESITE Cross-site cookie policy 'Lax'

Example:

SESSION_COOKIE_AGE = 1800  # 30 minutes
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_SAMESITE = 'Lax'

Session Storage Backends

You can change how and where session data is stored by updating SESSION_ENGINE:

Backend Engine Setting Description
Database (default) 'django.contrib.sessions.backends.db' Stores sessions in DB
Cached 'django.contrib.sessions.backends.cache' Fast, but volatile
File-based 'django.contrib.sessions.backends.file' Stores on filesystem
Cookie-based 'django.contrib.sessions.backends.signed_cookies' Stores data in encrypted cookies
Cache + DB fallback 'django.contrib.sessions.backends.cached_db' Cached with DB fallback

Real-World Use Case: Shopping Cart

Set cart items in session:

def add_to_cart(request, item_id):
    cart = request.session.get('cart', [])
    cart.append(item_id)
    request.session['cart'] = cart
    return HttpResponse("Item added to cart")

Retrieve cart:

def view_cart(request):
    cart = request.session.get('cart', [])
    return HttpResponse(f"Cart items: {cart}")

Inspecting Sessions

If you’re using the database backend, you can inspect session data in the DB:

SELECT * FROM django_session;

Use the Django shell to decode:

python manage.py shell
from django.contrib.sessions.models import Session
from django.utils import timezone

sessions = Session.objects.filter(expire_date__gte=timezone.now())
for session in sessions:
    data = session.get_decoded()
    print(data)

❌ Common Pitfalls

Problem Cause Fix
Session not saving No data was changed or modified Make sure session is modified before returning
KeyError on get Accessing missing key with request.session['key'] Use .get('key', default) instead
Session expires too early SESSION_COOKIE_AGE too low Increase the timeout
JavaScript can’t access session Cookie is HttpOnly Set SESSION_COOKIE_HTTPONLY = False (not recommended for sensitive data)
Session not persistent SESSION_EXPIRE_AT_BROWSER_CLOSE = True Set to False for persistence

Difference Between Sessions and Cookies

Feature Session Cookie
Stored In Server Client (browser)
Size Limit Large (server dependent) ~4KB
Security More secure Less secure
Access Server-side only Accessible from JS if not HttpOnly
Tamper Proof Yes No (unless signed manually)

Summary

Django sessions are a robust and easy-to-use mechanism for maintaining user state across requests. Whether you're building login systems, shopping carts, or preference tracking, sessions are a safe and scalable option.

✅ You now know:

  • How sessions work in Django

  • How to use sessions (set, get, delete)

  • How to configure and secure sessions

  • Real-world use cases and pitfalls to avoid