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
| Option | Description |
|---|---|
| max_age | Seconds until expiry |
| expires | Date/time of expiry |
| path | Cookie path |
| domain | Cookie domain |
| secure | HTTPS only |
| httponly | JavaScript 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
- Set and read cookies
- Set cookie with expiry
- Delete a cookie
- 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.