Sessions help remember who a user is while they browse your website. This makes the site feel personal and secure.
Session framework configuration in Django
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Django
In your Django settings.py file: # Enable session middleware MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', # other middleware ] # Choose session engine SESSION_ENGINE = 'django.contrib.sessions.backends.db' # default, stores sessions in database # Optional: session cookie settings SESSION_COOKIE_NAME = 'sessionid' SESSION_COOKIE_AGE = 1209600 # 2 weeks in seconds SESSION_COOKIE_SECURE = False # True if using HTTPS # Optional: session expiration SESSION_EXPIRE_AT_BROWSER_CLOSE = False
The SessionMiddleware must be in the MIDDLEWARE list for sessions to work.
You can change SESSION_ENGINE to store sessions in cache, files, or signed cookies.
Examples
Django
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'Django
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'Django
SESSION_COOKIE_AGE = 3600Django
SESSION_EXPIRE_AT_BROWSER_CLOSE = TrueSample Program
This example shows two simple views. One saves a value in the session, and the other reads it back.
Django
from django.http import HttpResponse def set_session(request): request.session['favorite_color'] = 'blue' return HttpResponse('Session data saved.') def get_session(request): color = request.session.get('favorite_color', 'not set') return HttpResponse(f'Favorite color is {color}.')
Important Notes
Sessions rely on cookies, so users must have cookies enabled in their browsers.
Be careful not to store large or sensitive data directly in sessions.
Always include SessionMiddleware before any middleware that uses sessions.
Summary
Sessions let Django remember user data between page visits.
Enable sessions by adding SessionMiddleware and choosing a session engine.
Configure session cookie settings to control how long sessions last and their security.
Practice
1. What is the main purpose of Django's session framework?
easy
Solution
Step 1: Understand session framework role
Django sessions store data to keep track of users as they move between pages.Step 2: Compare options with session purpose
Only To remember user data between different pages describes remembering user data between pages, which is the session's job.Final Answer:
To remember user data between different pages -> Option CQuick Check:
Sessions remember users = B [OK]
Hint: Sessions remember users across pages, not files or migrations [OK]
Common Mistakes:
- Confusing sessions with static file storage
- Thinking sessions only handle login
- Mixing sessions with database migrations
2. Which setting in
settings.py specifies the backend storage for sessions?easy
Solution
Step 1: Identify session backend setting
The setting that controls where sessions are stored isSESSION_ENGINE.Step 2: Review other options
Other options control cookie age, saving behavior, or expiration, not storage backend.Final Answer:
SESSION_ENGINE -> Option AQuick Check:
Backend storage = SESSION_ENGINE [OK]
Hint: SESSION_ENGINE sets storage backend, not cookie or expiration [OK]
Common Mistakes:
- Confusing SESSION_ENGINE with cookie age
- Mixing save behavior with storage backend
- Assuming expiration settings control storage
3. Given this
What happens when a user closes and reopens their browser?
settings.py snippet:SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SESSION_COOKIE_AGE = 1209600 # 2 weeks SESSION_EXPIRE_AT_BROWSER_CLOSE = False
What happens when a user closes and reopens their browser?
medium
Solution
Step 1: Analyze SESSION_EXPIRE_AT_BROWSER_CLOSE
It is set to False, so session cookies do not expire when browser closes.Step 2: Check SESSION_COOKIE_AGE
Set to 2 weeks, so session lasts that long unless user logs out.Final Answer:
The session is kept for 2 weeks and user stays logged in -> Option DQuick Check:
Expire at close = False means session kept [OK]
Hint: False expire at close means session lasts cookie age [OK]
Common Mistakes:
- Assuming session expires on browser close by default
- Confusing cache backend with database storage
- Thinking cookie deletion removes session data immediately
4. You set
SESSION_ENGINE = 'django.contrib.sessions.backends.file' but get errors about missing directories. What is the likely cause?medium
Solution
Step 1: Understand file backend requirements
The file backend stores sessions in files, needing a writable directory.Step 2: Identify cause of errors
If directory is missing or not writable, errors occur when saving sessions.Final Answer:
The session file directory does not exist or lacks write permission -> Option AQuick Check:
File backend needs writable directory [OK]
Hint: File backend needs writable folder, else errors occur [OK]
Common Mistakes:
- Assuming SESSION_ENGINE value syntax is wrong
- Forgetting sessions are built-in, no INSTALLED_APPS needed
- Blaming cookie age for file write errors
5. You want sessions to expire when the user closes the browser but also want to keep sessions for 1 hour if the browser stays open. Which settings combination achieves this?
hard
Solution
Step 1: Understand SESSION_EXPIRE_AT_BROWSER_CLOSE
Setting it to True makes the session expire when browser closes.Step 2: Understand SESSION_COOKIE_AGE
Setting it to 3600 seconds (1 hour) limits session lifetime if browser stays open.Final Answer:
SESSION_EXPIRE_AT_BROWSER_CLOSE = True and SESSION_COOKIE_AGE = 3600 -> Option BQuick Check:
Expire at close True + 1 hour age = A [OK]
Hint: Expire at close True + cookie age limits session time [OK]
Common Mistakes:
- Setting expire at close False when wanting session to end on close
- Using None for cookie age disables expiration
- Confusing cookie age with session storage backend
