Django Sessions and Cookies

HTTP, the protocol your browser uses to talk to a web server, is stateless — it forgets everything after each request. When you click a link and load a new page, the server has no memory of your previous visit. Sessions and Cookies are the two main tools Django uses to remember information about a user across multiple requests.

What is a Cookie?

A cookie is a small piece of text data that Django sends to the user's browser, and the browser stores it. Every time the browser makes a new request to the same website, it automatically sends the cookie back. This lets the server "remember" something about that specific user.

Example: A cookie is like a stamp on your hand at an entry gate. When you exit and come back in, the guard checks your stamp and knows you already paid for entry — without you needing to show your ticket again. The stamp (cookie) lives on your hand (browser) and is shown automatically each time.

What is a Session?

A Session is Django's preferred way of storing user-specific data on the server side. Instead of storing the actual data in the browser cookie, Django stores a unique session ID in the browser cookie. The real data is stored on the server (in the database). The browser only holds the tiny session ID — not the actual data.

Example: When you check your coat at a theatre, they give you a small numbered ticket (session ID in the cookie). The actual coat (session data) stays safe in the cloakroom (server). When you present your ticket later, they retrieve your coat using the number. Your ticket is tiny and useless on its own — the real information is stored safely by the theatre.

Cookie vs Session — Key Differences

  • Cookies: Data stored in the browser. Browser can see the data. Limited to about 4KB. Can expire at a set date.
  • Sessions: Data stored on the server. More secure — browser only sees a session ID. Can store larger amounts of data. Expires when the browser closes or after a set time.

Setting Up Sessions

Sessions are enabled by default in Django. Make sure these are in settings.py:


INSTALLED_APPS = [
    ...
    'django.contrib.sessions',   # <-- Must be present
    ...
]

MIDDLEWARE = [
    ...
    'django.contrib.sessions.middleware.SessionMiddleware',  # <-- Must be present
    ...
]

Also run migrations once so Django creates the sessions table in the database:


python manage.py migrate

Working with Sessions in Views

The session is available through request.session. It works like a Python dictionary — you can set, get, and delete keys.

Setting a Session Value


def set_preference(request):
    request.session['theme'] = 'dark'
    request.session['language'] = 'Hindi'
    return redirect('home')

Reading a Session Value


def home(request):
    theme = request.session.get('theme', 'light')   # 'light' is the default if not set
    language = request.session.get('language', 'English')
    return render(request, 'home.html', {'theme': theme, 'language': language})

Deleting a Specific Session Key


def clear_theme(request):
    if 'theme' in request.session:
        del request.session['theme']
    return redirect('home')

Clearing the Entire Session


def logout_user(request):
    request.session.flush()   # Deletes all session data and the session cookie
    return redirect('login')
Example: Using request.session is like using a private whiteboard at your desk in a library. You write notes for yourself (session['key'] = value), come back later and read them (session.get('key')), or wipe the board clean when done (session.flush()). Only you can see your whiteboard.

Session Expiry Settings

You can control how long a session lasts in settings.py:


# Session expires when the browser is closed (default behaviour)
SESSION_EXPIRE_AT_BROWSER_CLOSE = True

# Session expires after X seconds (e.g., 1 hour = 3600 seconds)
SESSION_COOKIE_AGE = 3600

# Refresh session timer on every request (extends the expiry)
SESSION_SAVE_EVERY_REQUEST = True

Practical Use Case — Shopping Cart with Sessions

A shopping cart is a classic example of sessions. Items are added across multiple pages, and the server must remember what is in the cart:


def add_to_cart(request, product_id):
    cart = request.session.get('cart', [])   # Get existing cart or start empty
    cart.append(product_id)                  # Add the new product
    request.session['cart'] = cart           # Save back to session
    request.session.modified = True          # Tell Django the session was changed
    return redirect('cart')

def view_cart(request):
    cart = request.session.get('cart', [])
    return render(request, 'cart.html', {'cart': cart})

def clear_cart(request):
    if 'cart' in request.session:
        del request.session['cart']
    return redirect('cart')

request.session.modified = True is important when you modify a mutable object (like a list) inside the session — it tells Django that the session has changed and needs to be saved.

Working with Cookies Directly

For simple, non-sensitive data, you can use cookies directly in Django. Unlike sessions, cookies are stored entirely in the browser.

Setting a Cookie in a View


from django.shortcuts import render
from django.http import HttpResponse

def set_cookie_view(request):
    response = HttpResponse("Cookie has been set!")
    response.set_cookie('visited', 'yes', max_age=3600)  # Expires in 1 hour
    return response

Reading a Cookie in a View


def home(request):
    visited_before = request.COOKIES.get('visited', 'no')
    return render(request, 'home.html', {'visited': visited_before})

Deleting a Cookie


def clear_cookie_view(request):
    response = HttpResponse("Cookie cleared!")
    response.delete_cookie('visited')
    return response
Example: Cookies are great for remembering small harmless preferences — like displaying a "Welcome back!" message on the home page after someone visited before. Since the data is stored in the browser, always avoid storing anything sensitive (like passwords or personal data) in cookies.

Session Storage Backends

Django can store session data in different places. The default is the database, but you can change it in settings.py:


# Default — stores sessions in the database (requires migrations)
SESSION_ENGINE = 'django.contrib.sessions.backends.db'

# Stores sessions in files on the server
SESSION_ENGINE = 'django.contrib.sessions.backends.file'

# Stores sessions in browser cookies (no server storage needed, 4KB limit)
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'

# Stores sessions in server memory (fast but lost on server restart)
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'

Quick Recap

  • Cookies — Small data stored in the browser. Good for non-sensitive preferences. Use response.set_cookie() and request.COOKIES.get().
  • Sessions — Data stored on the server. More secure. Only session ID is in the browser cookie. Use request.session['key'] = value.
  • Always use request.session.get('key', default) to avoid errors when a key does not exist.
  • Use request.session.modified = True after modifying a mutable session value like a list or dictionary.
  • Use request.session.flush() to clear all session data — useful for custom logout.
  • Never store sensitive data (passwords, payment info) in cookies — always use sessions.

Leave a Comment

Your email address will not be published. Required fields are marked *