When a user logs into your Django application, how does Django remember them across pages?
When you add an item to a cart, how does it stay there as you navigate?
The answer is sessions and cookies.
These two concepts allow Django to:
In this tutorial, you will learn how Django uses sessions and cookies, how to store data in them, and how to use them in real applications.
By the end of this tutorial, you will understand:
Before starting, you should already know:
A cookie is a small piece of data stored in the userβs browser.
Example uses:
Cookies are:
A session is a way to store data on the server for a specific user.
Instead of storing data in the browser, Django stores it on the server and gives the user a session ID stored in a cookie.
π So:
When a user logs in:
On each request:
This is how authentication works behind the scenes.
Django provides a dictionary-like object:
request.sessionYou can use it like a Python dictionary.
def set_session(request):
request.session['username'] = 'youssef'
request.session['role'] = 'admin'
return HttpResponse("Session data set")def get_session(request):
username = request.session.get('username')
role = request.session.get('role')
return HttpResponse(f"User: {username}, Role: {role}")Using .get() avoids errors if the key does not exist.
request.session['role'] = 'editor'del request.session['username']request.session.flush()This removes all session data and logs the user out.
if 'username' in request.session:
print("User exists in session")views.pyfrom django.http import HttpResponse
def visit_counter(request):
visits = request.session.get('visits', 0)
visits += 1
request.session['visits'] = visits
return HttpResponse(f"You have visited this page {visits} times.")This counts how many times a user visited the page.
By default, sessions expire when the browser closes.
You can control this.
request.session.set_expiry(3600) # 1 hourrequest.session.set_expiry(None)request.session.set_expiry(0)settings.pySESSION_COOKIE_AGE = 1209600 # 2 weeks
SESSION_SAVE_EVERY_REQUEST = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
Django can store sessions in different places:
Default (database):
SESSION_ENGINE = 'django.contrib.sessions.backends.db'Cookies are key-value pairs stored in the browser.
Example:
theme=dark
language=enThey are sent with every HTTP request.
from django.http import HttpResponse
def set_cookie(request):
response = HttpResponse("Cookie set")
response.set_cookie('theme', 'dark')
return response
def get_cookie(request):
theme = request.COOKIES.get('theme')
return HttpResponse(f"Theme: {theme}")response.delete_cookie('theme')
You can configure cookies:
response.set_cookie(
'theme',
'dark',
max_age=3600, # 1 hour
secure=True,
httponly=True
)max_age β expiration timesecure β only sent over HTTPShttponly β not accessible via JavaScript (security)| Feature | Sessions | Cookies |
|---|---|---|
| Storage | Server | Browser |
| Security | More secure | Less secure |
| Size | Large | Small |
| Usage | Authentication, cart, user data | Preferences, simple data |
π Rule:
def add_to_cart(request, product_id):
cart = request.session.get('cart', [])
cart.append(product_id)
request.session['cart'] = cart
return HttpResponse("Product added to cart")def view_cart(request):
cart = request.session.get('cart', [])
return HttpResponse(f"Cart: {cart}")def set_theme(request):
response = HttpResponse("Theme set")
response.set_cookie('theme', 'dark')
return response<body class="{{ request.COOKIES.theme }}">
Django allows session access in templates:
<p>User: {{ request.session.username }}</p><p>Theme: {{ request.COOKIES.theme }}</p>β Bad:
response.set_cookie('password', '123456')βοΈ Good:
request.session['user_id'] = user.idSESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = TrueSESSION_COOKIE_HTTPONLY = TrueSessions are server-side; cookies are client-side.
Usually automatic, but important in some cases.
Cookies have size limits.
Always enable HTTPS-related settings.
Track last visit:
from datetime import datetime
from django.http import HttpResponse
def last_visit(request):
last = request.session.get('last_visit')
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
request.session['last_visit'] = now
if last:
return HttpResponse(f"Last visit: {last}")
return HttpResponse("This is your first visit")In this tutorial, you learned:
request.session behaves like a dictionaryset_cookie()
A. Browser
B. Server
C. Template
D. URL
A. Database tables
B. Python code
C. Small key-value data in browser
D. Views
A. request.data
B. request.session
C. request.cookie
D. request.storage
A. set_cookie()
B. add_cookie()
C. create_cookie()
D. save_cookie()
A. Cookies
B. Sessions
C. Both equal
D. None
Next tutorial:
Tutorial: Pagination in Django
Subject: Splitting long lists into pages for better UX.