# Session configuration
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
SESSION_CACHE_ALIAS = 'default'
SESSION_COOKIE_AGE = 1209600 # 2 weeks in seconds
SESSION_COOKIE_SECURE = True # HTTPS only
SESSION_COOKIE_HTTPONLY = True # No JavaScript access
SESSION_COOKIE_SAMESITE = 'Lax'
SESSION_SAVE_EVERY_REQUEST = False # Only save if modified
def add_to_cart(request, product_id):
cart = request.session.get('cart', {})
cart[str(product_id)] = cart.get(str(product_id), 0) + 1
request.session['cart'] = cart
request.session.modified = True # Force save
return redirect('cart:view')
def set_session_expiry(request):
# Expire when browser closes
request.session.set_expiry(0)
# Expire in 5 minutes
request.session.set_expiry(300)
# Expire at specific datetime
from datetime import datetime, timedelta
request.session.set_expiry(datetime.now() + timedelta(hours=1))
def clear_session(request):
request.session.flush() # Delete session and create new one
Sessions store user state across requests. Django supports database, cache, file, and cookie-based sessions. I use cacheddb for read performance with database persistence. For APIs, I avoid sessions in favor of token auth. The request.session dict-like object stores arbitrary data. I set expiry with `setexpiry(). For security, I useSESSIONCOOKIESECUREandSESSIONCOOKIEHTTPONLY` in production. Custom session backends can store sessions in Redis or other stores. This enables features like shopping carts and multi-step forms.