What is Cookie?

A cookie is a small piece of text file that contains data. The data in the cookie is often a random key or token. The server use a cookie to identify a client. Specific cookie known as HTTP cookie is used to identify a specific user and to keep track of that user’s movements within the site.

Suppose, you have visited a shop for the first time & bought some cloths of your favorite color. The owner has given you a membership card. Now, if you go again, he might not remember your face but he will recognize the card issued by his shop & can find your buying history & can serve you well. Here, the shop is the web server, you are the client and the membership card is the cookie. As the membership card will not be valid for other shops similarly a cookie won’t be valid for a different website.

Using Cookies in Django

In django we have a dictionary which is HttpRequest.COOKIES. Django stores all cookies here. Key & Values of the dictionary are strings.

key – The name of the cookie

value – The value of the cookie.

Create Cookie

The set_cookie() –  method is used to set/create/send cookies.

Full Syntax:

HttpResponse.set_cookie(key, value="", max_age = None,            expires=None, path=”/”, domain=None, secure = False, httponly=False, samesite=None)

Only name & value are required-arguments; others are optional. If optional values are not passed, predefined values will be set.

Example: set_cookie(“username”, “arafat”)

We will describe each of the arguments:

key= This is the name of the cookie.

value – this sets the value of the cookie, the client’s computer stores its value.

max_age – lifetime of the cookie, value is given in seconds. Default is None. Sets the expiration time. If expires is not specified. The max_age will be calculated.

max_age = 3600 means the cookie will last for one hour (60*60)

expires = it describes the expiration time of the cookie. It should be string format ‘DD-MM-YYYY HH:MM:SS’ GMT or a datetime.datetime object in UTC.

path ­– path can be / (root) or /mydir (directory)


set_cookie(“username”, “arafat”, “/”)

set_cookie(“username”, ‘arafat’, ‘/home’)

domain – Use the domain if you want to set a cross-domain cookie.

domain = ‘example.com’

The above example will set a cookie that is readable by the domains www.example.com, blog.example.com, etc. Otherwise, a cookie will only be readable by the domain that set it.

secure– Cookie to only be transmitted over secure protocol as https. When set to TRUE the cookie will only be set if a secure connection exists.

httponly – HttpOnly is a flag included in a Set-Cookie HTTP response header.Use httponly = True if you want to prevent client-side JavaScript from having access to the cookie.

samesite Strict or Lax. It tells the browser to send this cookie when performing a cross-origin request. All browser do not support SameSite. So it’s not a replacement for Django’s CSRF protection but rather a defense-in-depth measure.


Let’s set a cookie in our browser…

def set_cookie(request):
    response =render(request,'set_cookies.html')
    return response

I am using chrome browser. In chrome you can check your cookies in ‘Settings/Privacy and security/Cookies and other site data‘ There check the ‘Allow all cookies‘ in General Settings, otherwise your code might not work. You will get an option ‘See all cookies and site data’ where you will find all the cookies set in your browser. I have cleared all of my cookies. So it’s blank now.



Let’s run the server and check the view. – after hitting this url go to the ‘See all cookies and site data’ tab. You should see some data like below.

Let’s check what’s inside!

The key (username) & the value (arafat) of our cookies is saved in the browser.

Update Cookie

We have saved our cookie. Now we will update the value of our cookie. It is not different from setting a cookie. We will use the same method set_cookie but at this time the key will be same as before only the value will be changed.

def update_cookie(request):
    response = render(request,'update_cookies.html')
    return response



After hitting this url Django will update our cookie…

Get Cookie

Let’s retrieve the value of our cookie. To get the value we use request.COOKIES.get() or request.COOKIES.

def get_cookie(request):
    username = request.COOKIES.get('username')
    context = {
    return render(request,'get_cookies.html',context )



We will need to add some html in our ‘get_cookies.html‘ to show the value.

<h3>{{ username }}</h3>

Now, we will see the output in our browser

Delete Cookie

We have seen how to set, update & get cookies. Now let’s delete the cookie. Hitting the ‘delete-cookie’ url will delete the cookie that we have set & our cookie storage will get empty.

def delete_cookie(request):
    response = render(request,'delete_cookies.html')
    return response


path('delete-cookie/', views.delete_cookie), hitting this url let’s check our browser cookies. It’s fully empty again…

If you are done with cookies. It’s time to learn about Sessions. Know about Django Sessions here.

+ posts

Author | Python-Django Developer

+ posts

Full-stack Developer (Python | Django | React | React-Native | Angular | Vue)