Django Cookies

Summary: in this tutorial, you’ll learn about cookies and how to set and get cookies in Django web applications.

Introduction to HTTP cookies

When a web server interacts with many different browsers at the same time, it needs to identify which browser a specific request came from.

Because the HTTP request/response is stateless, all web browsers look identical. To identify the web browsers, the web server uses cookies.

Technically, cookies are text files with a small piece of data that the web server sends to a web browser. The web browser may store the cookie and send it back to the web server in subsequent requests.

Note that the web browser only sends back cookies that were originally set by the same web server.

By comparing the cookies, the web server can identify that the requests come from the same web browser.

Cookies have expiration dates. Some may last for years while others are short-term and expired as soon as you close the web browsers.

Django Cookies

Django allows you to set, read, and delete cookies via methods of the HttpResponse object.

Setting a cookie

To set a cookie, you use the set_cookie() method of the HttpResponse object:

set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=NoneCode language: Python (python)

In this method:

  • key is the cookie name.
  • value is a string that represents the cookie’s value.
  • max_age can be a timedelta object or an integer that denotes the number of seconds that specifies how long the cookie should expire. It defaults to None that expires cookie once you close the browser.
  • expires should be either a datetime object in UTC or a string in the format "Wdy, DD-Mon-YY HH:MM:SS GMT".
  • Use secure=True when you want the web browser to send the cookie to the server if the request is HTTPS only.
  • Use httponly=True if you don’t want the client-side JavaScript to access the cookie.
  • Use samesite='None' (string) to allow the cookie to be sent with all same-site and cross-site requests.

Deleting a cookie

To delete a cookie, you use the delete_cookie() method of the HttpResponse object:

delete_cookie(key, path='/', domain=None, samesite=None)Code language: Python (python)

The delete_cookie() method deletes a cookie with a specified name. It fails silently if the key doesn’t exist.

Note that the path and domain must have the same values as you used in the set_cookie() method or the cookie will not be deleted.

Reading cookies

To access all cookies sent by the web browser, you use the COOKIES property of the HttpRequest object.

request.COOKIESCode language: Python (python)

To access a cookie by a key, you pass the cookie name to the request.COOKIES dictionary. For example:

request.COOKIES['cocoa']Code language: Python (python)

If the cookie 'cocoa' doesn’t exist, Django will throw an error.

To avoid the error, you can use the get() method of the dictionary to get a cookie if it exists or get a default value otherwise. For example:

request.COOKIES.get('cocoa',1)Code language: Python (python)

The code will return 1 if the cookie with the name 'cocao' doesn’t exist.

Django cookies example

We’ll use a cookie to store whether the web browser has visited the site. When the visitor visits the site for the first time, it’ll show a message:

Welcome to my website!Code language: plaintext (plaintext)

And from the second time, it’ll check the cookie and show the following message if the cookie with the name visited is available:

Welcome back!Code language: plaintext (plaintext)

First, define a new entry in the urlpatterns of the urls.py file of your app:

urlpatterns = [
    path('', views.home, name='home'),
]Code language: Python (python)

When you open the http://127.0.0.1:8000/, Django will execute the home() function in the views.py file.

Second, define the home() function in the views.py file:

def home(request):
    visited = request.COOKIES.get('visited')
    if visited:
        response = HttpResponse('Welcome back!')
    else:
        response = HttpResponse('Welcome to my website!')
        response.set_cookie('visited', True)

    return responseCode language: Python (python)

In the home() function, we read the cookie with the name visited. If the cookie with the name visited does not exist, the homepage will display the message:

Welcome to my website!Code language: plaintext (plaintext)

Otherwise, it’ll show the message:

Welcome back!Code language: plaintext (plaintext)

Also, we set the visited cookie to True.

If you view the cookie in the web browser, you’ll see the cookie with the name visited like this:

django cookies example

Summary

  • A cookie is a piece of data that the web server sends to the web browser and the web browser may store it or not.
  • The web browser sends the cookie back to the web server in the subsequent requests in the header of the HTTP request.
  • Use the set_cookie() function of the HttpResponse object to set a cookie in Django.
  • Use the delete_cookie() method of the HttpResponse object to delete a cookie.
  • Use the request.COOKIES dictionary to read all cookies sent by the web browser.
Did you find this tutorial helpful ?