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:

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:

Prerequisites

Before starting, you should already know:

1. What Are Cookies?

A cookie is a small piece of data stored in the user’s browser.

Example uses:

Cookies are:

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:

3. How Django Uses Sessions

When a user logs in:

  1. Django creates a session
  2. stores user ID in the session
  3. sends a cookie with the session ID to the browser

On each request:

This is how authentication works behind the scenes.

4. Session Basics in Django

Django provides a dictionary-like object:

request.session

You 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 hour

Never 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:

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=en

They 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

19. Sessions vs Cookies

FeatureSessionsCookies
StorageServerBrowser
SecurityMore secureLess secure
SizeLargeSmall
UsageAuthentication, cart, user dataPreferences, simple data

πŸ‘‰ Rule:

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 response

Template 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.id

Use secure cookies in production

SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

Use HTTP-only cookies

SESSION_COOKIE_HTTPONLY = True

25. 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:

 

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.