0
0
DjangoHow-ToBeginner · 4 min read

How to Use Session in Django: Simple Guide with Examples

In Django, you use request.session to store and access session data as a dictionary. You can save data by assigning values to keys like request.session['key'] = value and retrieve it with request.session.get('key'). Sessions help keep user data between page visits without needing to log in each time.
📐

Syntax

Django sessions are accessed via the request.session object, which behaves like a Python dictionary.

  • request.session['key'] = value: Store data in the session.
  • value = request.session.get('key'): Retrieve data safely.
  • request.session.pop('key', default): Remove data from session.
  • request.session.clear(): Clear all session data.
python
def view(request):
    # Store data
    request.session['favorite_color'] = 'blue'

    # Retrieve data
    color = request.session.get('favorite_color', 'red')

    # Remove data
    request.session.pop('favorite_color', None)

    # Clear all session data
    request.session.clear()
💻

Example

This example shows a Django view that sets a user's favorite color in the session and then reads it back to display in a response.

python
from django.http import HttpResponse

def favorite_color_view(request):
    # Set favorite color in session
    request.session['favorite_color'] = 'green'

    # Get favorite color from session
    color = request.session.get('favorite_color', 'unknown')

    return HttpResponse(f"Your favorite color is {color}.")
Output
Your favorite color is green.
⚠️

Common Pitfalls

Common mistakes when using Django sessions include:

  • Not enabling sessions middleware in settings.py. You must have 'django.contrib.sessions.middleware.SessionMiddleware' in MIDDLEWARE.
  • Trying to store non-serializable objects in session (only JSON-serializable data like strings, numbers, lists, dicts are safe).
  • Forgetting to save session changes explicitly is not needed; Django saves automatically when you modify request.session.
  • Assuming session data is secure; never store sensitive info without encryption.
python
## Wrong: Storing a complex object
request.session['user'] = UserObject  # This will cause errors

## Right: Store simple data
request.session['user_id'] = user.id
📊

Quick Reference

Remember these key points when working with Django sessions:

  • Sessions use cookies to track users but store data on the server.
  • Session data acts like a dictionary attached to request.session.
  • Always check if a key exists using get() to avoid errors.
  • Clear sessions when users log out to protect privacy.

Key Takeaways

Use request.session like a dictionary to store and retrieve user data across requests.
Ensure SessionMiddleware is enabled in your Django settings to use sessions.
Only store simple, serializable data types in sessions to avoid errors.
Use get() to safely access session data without crashing.
Clear session data on logout to keep user information private.