BudiBadu Logo
Samplebadu

Django by Example: Cookie Data Handling

Django 5.0+

Cookies are small pieces of data stored in the user's browser. This example shows how to set, retrieve, and delete cookies securely, including signed cookies that cannot be tampered with.

Code

def set_cookie_view(request):
    response = HttpResponse("Cookie Set")
    
    # 1. Simple Cookie
    # max_age is in seconds
    response.set_cookie('favorite_color', 'blue', max_age=3600)
    
    # 2. Signed Cookie (Tamper-proof)
    # User can see it, but cannot modify it
    response.set_signed_cookie('discount_code', 'SUMMER2023', salt='promo')
    
    # 3. Secure Cookie (HTTPS only)
    response.set_cookie(
        'session_id', 
        '12345', 
        secure=True, 
        httponly=True, 
        samesite='Lax'
    )
    
    return response

def get_cookie_view(request):
    # 4. Read Cookies
    color = request.COOKIES.get('favorite_color', 'red')
    
    try:
        code = request.get_signed_cookie('discount_code', salt='promo')
    except BadSignature:
        code = "Invalid Code"
        
    return HttpResponse(f"Color: {color}, Code: {code}")

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

Explanation

Cookies are the mechanism that allows websites to remember stateful information. While sessions are stored on the server, cookies are stored on the client. Django provides a wrapper around the HTTP cookie protocol, allowing you to set and read cookies easily.

For security, you should always use:

  • httponly=True: Prevents JavaScript from accessing the cookie, mitigating XSS attacks.
  • secure=True: Ensures the cookie is only sent over HTTPS.
  • samesite='Lax' or 'Strict': Prevents CSRF attacks by restricting when cookies are sent with cross-site requests.

Django also offers Signed Cookies. These are cryptographically signed with your SECRET_KEY. The user can see the value, but if they change it, the signature will fail validation. This is useful for storing non-sensitive data that you want to trust (e.g., a discount code).

Code Breakdown

6
response.set_cookie(). This adds the Set-Cookie header to the HTTP response. max_age controls how long the browser keeps it. If omitted, it's a session cookie (deleted when browser closes).
10
set_signed_cookie. The value stored in the browser will look like SUMMER2023:1s5...signature.... The user can see "SUMMER2023" but cannot change it to "WINTER2024" without invalidating the signature.
25
request.COOKIES. A standard dictionary containing all cookies sent by the browser. Remember, this data comes from the user and is untrusted.
28
request.get_signed_cookie(). This verifies the signature using your project's SECRET_KEY. If the signature is invalid, it raises BadSignature.
37
response.delete_cookie(). To delete a cookie, you must call this method on the response object. It effectively sets the cookie's expiration date to the past.