Django Cookies
A cookie is a small value kept by the browser. The app writes it, and the browser sends it back with each request.
Set the cookie
The view makes a response and adds a cookie named flavour, value mint.
def set_cookie(request):
response = HttpResponse("Cookie set")
response.set_cookie("flavour", "mint")
return responseRead the cookie
The view looks for flavour in the cookies that arrived. The default shows when none arrives.
def read(request):
return HttpResponse(request.COOKIES.get("flavour", "no cookie"))Look at the cookie in the response
The set response carries the cookie. The print shows its value.
client = Client()
response = client.get("/set")
print(response.cookies["flavour"].value)Set, then read
The test client opens /set first, which saves the cookie. The next ask reads the cookie back.
client.get("/set")
print(client.get("/read").content.decode())Example
import django
from django.conf import settings
settings.configure(DEBUG=True, SECRET_KEY="key", ROOT_URLCONF=__name__, ALLOWED_HOSTS=["*"])
django.setup()
from django.http import HttpResponse
from django.urls import path
from django.test import Client
def set_cookie(request):
response = HttpResponse("Cookie set")
response.set_cookie("flavour", "mint")
return response
def read(request):
return HttpResponse(request.COOKIES.get("flavour", "no cookie"))
urlpatterns = [path("set", set_cookie), path("read", read)]
client = Client()
response = client.get("/set")
print(response.cookies["flavour"].value)
print(client.get("/read").content.decode())Key points
- response.set_cookie puts a cookie on a response.
- request.COOKIES holds the cookies the browser sent.
- A cookie carries one name and one value.
- Cookies hold small choices, like a flavour.
- A cookie is a small note the browser holds.
In this example, the setup lines configure Django. The /set view makes a response and adds a cookie named flavour, value mint. The /read view reads the cookie back. The test client visits /set first, so the cookie gets stored. The prints show the cookie value from the response and then from the read page.
Note
A cookie rides along with every request after it is set.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How does a view set a cookie?