</>
Skip to content
Django lessons (25/43)

Django — Cookies

Setting Cookies

def my_view(request):
    response = HttpResponse("Hello")
    response.set_cookie('username', 'john', max_age=3600)
    return response

Reading Cookies

def my_view(request):
    username = request.COOKIES.get('username', 'Guest')
    return HttpResponse(f"Hello, {username}")

Deleting Cookies

def my_view(request):
    response = HttpResponse("Cookie deleted")
    response.delete_cookie('username')
    return response

Cookie Options

OptionDescription
max_ageSeconds until expiry
expiresDate/time of expiry
pathCookie path
domainCookie domain
secureHTTPS only
httponlyJavaScript inaccessible

Signed Cookies

# settings.py
SECRET_KEY = 'your-secret-key'

# Setting signed cookie
response.set_signed_cookie('username', 'john', salt='username')

# Reading signed cookie
username = request.get_signed_cookie('username', salt='username')

Mini Practice

  1. Set and read cookies
  2. Set cookie with expiry
  3. Delete a cookie
  4. Use signed cookies for security

Up Next

Continue with Messages — displaying messages to users.

Related Topics

Frequently Asked Questions about Cookies

What is Cookies in Django?

Cookies is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Cookies?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Cookies.

Why is Cookies important in Django?

Cookies is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.