Introduction
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:
- remember users between requests
- store temporary data
- manage login state
- personalize user experience
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.
What You Will Learn
By the end of this tutorial, you will understand:
- what cookies are
- what sessions are
- how Django uses sessions internally
- how to store and retrieve session data
- how to create and read cookies
- the difference between sessions and cookies
- best practices for using them securely
Prerequisites
Before starting, you should already know:
- Django authentication basics
- views and templates
- request and response cycle
1. What Are Cookies?
A cookie is a small piece of data stored in the user’s browser.
Example uses:
- remembering language preference
- storing a theme (dark/light mode)
- tracking user behavior
Cookies are:
- stored on the client (browser)
- sent with every request to the server
2. What Are Sessions?
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:
- cookie → stores session ID
- session → stores actual data on the server
3. How Django Uses Sessions
When a user logs in:
- Django creates a session
- stores user ID in the session
- sends a cookie with the session ID to the browser
On each request:
- Django reads the session ID from the cookie
- loads the session data
- knows which user is logged in
This is how authentication works behind the scenes.
4. Session Basics in Django
Django provides a dictionary-like object:
request.sessionYou can use it like a Python dictionary.
5. Storing Data in Session
Example
def set_session(request):
request.session['username'] = 'youssef'
request.session['role'] = 'admin'
return HttpResponse("Session data set")6. Retrieving Session Data
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.
7. Updating Session Data
request.session['role'] = 'editor'8. Deleting Session Data
Delete a specific key
del request.session['username']Clear entire session
request.session.flush()This removes all session data and logs the user out.
9. Check if Key Exists
if 'username' in request.session:
print("User exists in session")10. Session Example: Visit Counter
views.py
from 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.
11. Session Expiry
By default, sessions expire when the browser closes.
You can control this.
Set session expiry (in seconds)
request.session.set_expiry(3600) # 1 hourNever expire (until manually cleared)
request.session.set_expiry(None)Expire on browser close
request.session.set_expiry(0)12. Session Configuration
settings.py
SESSION_COOKIE_AGE = 1209600 # 2 weeks
SESSION_SAVE_EVERY_REQUEST = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
13. Where Sessions Are Stored
Django can store sessions in different places:
- database (default)
- cache (Redis, Memcached)
- file system
- signed cookies
Default (database):
SESSION_ENGINE = 'django.contrib.sessions.backends.db'14. What Are Cookies (Deep Dive)?
Cookies are key-value pairs stored in the browser.
Example:
theme=dark
language=enThey are sent with every HTTP request.
15. Creating Cookies in Django
from django.http import HttpResponse
def set_cookie(request):
response = HttpResponse("Cookie set")
response.set_cookie('theme', 'dark')
return response
16. Reading Cookies
def get_cookie(request):
theme = request.COOKIES.get('theme')
return HttpResponse(f"Theme: {theme}")17. Deleting Cookies
response.delete_cookie('theme')
18. Cookie Options
You can configure cookies:
response.set_cookie(
'theme',
'dark',
max_age=3600, # 1 hour
secure=True,
httponly=True
)Important options
max_age→ expiration timesecure→ only sent over HTTPShttponly→ not accessible via JavaScript (security)
19. Sessions vs Cookies
| Feature | Sessions | Cookies |
|---|---|---|
| Storage | Server | Browser |
| Security | More secure | Less secure |
| Size | Large | Small |
| Usage | Authentication, cart, user data | Preferences, simple data |
👉 Rule:
- use sessions for important data
- use cookies for simple client-side data
20. Real Example: Shopping Cart (Session)
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")View Cart
def view_cart(request):
cart = request.session.get('cart', [])
return HttpResponse(f"Cart: {cart}")21. Real Example: Theme Preference (Cookie)
def set_theme(request):
response = HttpResponse("Theme set")
response.set_cookie('theme', 'dark')
return responseTemplate usage
<body class="{{ request.COOKIES.theme }}">
22. Using Sessions in Templates
Django allows session access in templates:
<p>User: {{ request.session.username }}</p>23. Using Cookies in Templates
<p>Theme: {{ request.COOKIES.theme }}</p>24. Security Best Practices
Do NOT store sensitive data in cookies
❌ Bad:
response.set_cookie('password', '123456')Use sessions for sensitive data
✔️ Good:
request.session['user_id'] = user.idUse secure cookies in production
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = TrueUse HTTP-only cookies
SESSION_COOKIE_HTTPONLY = True25. Common Mistakes
Confusing sessions and cookies
Sessions are server-side; cookies are client-side.
Forgetting to save session changes
Usually automatic, but important in some cases.
Storing large data in cookies
Cookies have size limits.
Not using secure settings in production
Always enable HTTPS-related settings.
26. Mini Project Example
Login Tracking System
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")27. Summary
In this tutorial, you learned:
- cookies store small data in the browser
- sessions store data on the server
- Django uses sessions for authentication
request.sessionbehaves like a dictionary- cookies are created with
set_cookie() - sessions are safer for sensitive data
- sessions and cookies are essential for user state management
28. Mini Quiz
1. Where are sessions stored?
A. Browser
B. Server
C. Template
D. URL
2. What does a cookie store?
A. Database tables
B. Python code
C. Small key-value data in browser
D. Views
3. How do you access session data?
A. request.data
B. request.session
C. request.cookie
D. request.storage
4. Which method creates a cookie?
A. set_cookie()
B. add_cookie()
C. create_cookie()
D. save_cookie()
5. Which is more secure?
A. Cookies
B. Sessions
C. Both equal
D. None
29. What Comes Next?
Next tutorial:
Tutorial: Pagination in Django
Subject: Splitting long lists into pages for better UX.
💬 Comments
No comments yet. Be the first to comment!
Login to comment.