What is Cookie?

A cookie is a small piece of data stored in the user’s browser which is sent by the server. They are commonly used to store user preferences.

This is how cookies work in general:

  • The browser sends the request to the server.
  • The server sends the response along with one or more cookie to the browser.
  • The browser saves the cookie it received from the server. From now on, the browser will send this cookie to the server, every time a request is made to the server. The browser will keep sending the cookie to the server along with each request until the cookie expires.
  • When the cookie expires, it is removed from the browser.

Creating Cookies

We can create cookies using the set_cookie() method of the request object. The syntax of the method is:

Syntax: 

set_cookie(name, value, max_age=None)
  • name: name of the cookie
  • value: value you want to store in the cookie
  • max_age: age of the cookie in seconds. After that, it will expire. It is an optional argument, if not given then the cookie will exist until the browser is closed.

Example:

def setcookie(request):
    html = HttpResponse("<h1>How to set cookie by raturi</h1>")

    if request.COOKIES.get('visit_count'):
        message = 'Thanks for visiting again'
        value = int(request.COOKIES.get('visit_count')) + 1
    else:
        value = 1
        message = "Welcome for the first time"
    
    html.set_cookie('visit_count', value)
    html.set_cookie('visitor_message', message)
    return html

Reading Cookies

Cookies pass to the particular website every time the client makes a request. Therefore, server every time receives a cookie alongside the request. Django makes it very easy for us to retrieve data from a cookie.

very request object in Django has a COOKIE attribute which acts like a dictionary. We can use COOKIE to access a cookie value like this:

def read_cookie(request):
    show = request.COOKIES['visit_count']
    ...

Deleting Cookies

Django provides you with easy methods for deleting cookies. As we used set_cookie() to create cookies, we can also delete cookies using a similar function, delete_cookie()

def delete_cookie(request):
    if request.COOKIES.get('visit_count'):
       response.delete_cookie("visits")
    ...

Summary

Make some codes and edit this one to be familiar with the topics we have covered until this tutorial.

This tutorial covered most of the basics of cookies and how you can use them on Django. Using some right level of Python, now you are ready to make your cookies and use them as much as you want. But as a developer, you will need more knowledge of the norms and laws when you are using cookies on a hosted server like the ones where the website asks for your permission for accepting cookies.