Django Cookies Handling – A Complete Guide

Last updated 1 month, 2 weeks ago | 148 views 75     5

Tags:- Python Django

Cookies are small pieces of data stored in the user's browser to track sessions, store preferences, or perform authentication. Django provides a straightforward API for reading and writing cookies securely.


What Are Cookies?

Cookies are:

  • Stored in the user's browser.

  • Sent along with every request to the same domain.

  • Often used for:

    • Remembering user preferences

    • Maintaining login sessions

    • Tracking activity (with user consent)


Working with Cookies in Django

Setting a Cookie

Use the HttpResponse.set_cookie() method:

from django.http import HttpResponse

def set_cookie_view(request):
    response = HttpResponse("Cookie Set")
    response.set_cookie('favorite_color', 'blue')
    return response

Optional Parameters:

Parameter Description
key Cookie name
value Cookie value
max_age Time in seconds until the cookie expires
expires Specific date/time for expiration
path URL path to which the cookie applies
domain Domain to which the cookie applies
secure Send only over HTTPS
httponly Prevent access via JavaScript
samesite Control cross-site sending (Lax, Strict, or None)

Example with parameters:

response.set_cookie(
    key='user_id',
    value='12345',
    max_age=3600,  # 1 hour
    httponly=True,
    secure=True,
    samesite='Lax'
)

Getting a Cookie

Use request.COOKIES.get():

def get_cookie_view(request):
    color = request.COOKIES.get('favorite_color', 'default_color')
    return HttpResponse(f"Favorite color is {color}")

Always provide a default to avoid errors if the cookie is missing.


Deleting a Cookie

Use delete_cookie() on the response:

def delete_cookie_view(request):
    response = HttpResponse("Cookie Deleted")
    response.delete_cookie('favorite_color')
    return response

This tells the browser to expire the cookie immediately.


Real-World Example: Remembering a Theme Choice

1. Set Theme Preference

def set_theme_view(request, theme):
    response = redirect('home')
    response.set_cookie('theme', theme, max_age=60*60*24*30)  # 30 days
    return response

2. Read Theme in Views

def home_view(request):
    theme = request.COOKIES.get('theme', 'light')
    return render(request, 'home.html', {'theme': theme})

3. Apply Theme in Template

<body class="{{ theme }}">
    <!-- Your content here -->
</body>

Secure Cookie Settings

Setting Why it matters
httponly=True Prevents access via JavaScript (protects against XSS)
secure=True Cookie only sent over HTTPS
samesite='Lax' or 'Strict' Prevents CSRF attacks
max_age or expires Controls cookie lifetime

Best Practice Example:

response.set_cookie(
    'session_id',
    'XYZ123',
    max_age=3600,
    secure=True,
    httponly=True,
    samesite='Lax'
)

❌ Common Pitfalls

Problem Cause Solution
Cookie not setting Browser blocked it or secure=True on HTTP Use HTTPS or remove secure=True in dev
Cookie not found Wrong key or expired Check spelling, set max_age, or inspect browser dev tools
JavaScript can't read cookie httponly=True Set httponly=False if JS access is needed (with caution)
Cookie size exceeded Limit exceeded (~4KB) Store only minimal data in cookies

Cookies vs Sessions in Django

Feature Cookie Session
Stored in Browser Server-side
Secure Less secure (unless encrypted) More secure
Size limit ~4KB Larger
Tamper-proof? No Yes (if using signed cookies)
Use for Small user preferences Authentication, user data

Django’s session framework actually uses cookies under the hood — storing only a session key in a cookie and storing the rest in the database (or other backends).


Debugging Cookies

  • Use browser DevTools → Application → Cookies to inspect.

  • Use print(request.COOKIES) in views for quick debugging.

  • Check server response headers for Set-Cookie.


Summary

Django makes handling cookies simple and secure with its built-in methods. Cookies are great for storing lightweight, client-side data such as user preferences or themes.

✅ You now know how to:

  • Set, get, and delete cookies

  • Secure cookies with secure, httponly, and samesite

  • Use cookies in real apps like theme switching

  • Avoid common pitfalls and debug effectively