Sessions help remember who a user is while they browse your website. This makes the site feel personal and secure.
0
0
Session framework configuration in Django
Introduction
When you want to keep a user logged in as they move between pages.
To store temporary data like items in a shopping cart.
To remember user preferences during a visit.
When you need to protect pages so only certain users can see them.
To track user activity without asking them to log in every time.
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
This stores session data in your cache for faster access.
Django
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'This stores session data in cookies on the user's browser, signed for security.
Django
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'Sets session cookie to expire after 1 hour (3600 seconds).
Django
SESSION_COOKIE_AGE = 3600Ends the session when the user closes their browser.
Django
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}.')
OutputSuccess
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.