Cookies Handling in Django

How to handle cookies in Django. Sometimes you might want to store some data on a per-site-visitor basis as per the requirements of your web application.

Always keep in mind, that cookies are saved on the client-side and depending on your client browser security level, setting cookies can at times work and at times might not.

A cookie is a small piece of text data set by a Web server that resided on the client’s machine.

To illustrate cookies handling in Django, let’s create a system that will have setcookies, getcookies and delcookies function. The system will keep you logged in for X minute of time, and beyond that time, you will be out of the app.

Coding the app

As usual, we need to deal with some cookies. So, we need to create the app and create it according to the following tree.

  • To do so, look for the file urls.py in your app folder and add the code below:-
from django.contrib import admin
from django.urls import path
from student import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('set/',views.setcookie),
    path('get/',views.getcookie),
    path('del/',views.delcookie),
]

Creating Cookies

  • set_cookie() : is used to set/create/sent cookies.

Syntax:

HttpResponse.set_cookie(key,value="",max_age=None,expires=None,path='/',domain=None,secure=False,httponly=False,samesite=None)
  • Where the key is the name of the cookie and value is the value set to the cookie.
  • Now, let’s try to code the setcookie.html code:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Set Cookie</title>
</head>
<body>
    <h4>Cookie Set!!!!</h4>
</body>
</html>
  • The following code is used to set the cookie in views.py which expires when the browsing session ends:
from django.shortcuts import render

def setcookie(request):
    response = render(request,'student/setcookie.html')
    response.set_cookie('name', 'bipasha')
    return response
  • First, run the server/set/ and you will get the following output:

  • So the output for the following cookie will be:

  • To set the cookie which will expire after a specific time the code goes like this:
from django.shortcuts import render

# Create your views here.
def setcookie(request):
    response = render(request,'student/setcookie.html')
    response.set_cookie('name', 'bipasha',max_age=60)
    return response
  • Here we have set the time of 60sec expiry, which is set by max_age=60, you can keep time accordingly. So the output will be:

  • To set the cookie which expires after a certain number of days, the code goes like this:
from django.shortcuts import render
from datetime import datetime,timedelta
# Create your views here.
def setcookie(request):
    response = render(request,'student/setcookie.html')
    response.set_cookie('name', 'Bipasha', expires=datetime.utcnow() + timedelta(days=2))
    return response
  • Here, we have changed the name of the cookie and set the expiry date of the cookie after 2 days, so you can likewise change the cookie name and add the expiry

Reading/Accessing the Cookie

  • HttpRequest.COOKIES: A dictionary containing all cookies, where keys and values are strings.
  • Syntax: request.COOKIES[‘name’]
  • When we assign a new value to a cookie, the current cookie is not replaced. The new cookie is parsed and its name-value pair is appended in the list. The exception is when you assign a new cookie with the same name (and same domain and path) as a cookie that already exists. In this case, the old value is replaced with the new.
  • Now, let’s try to code the getcookie.html code:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Get Cookie</title>
</head>
<body>
    <h4>Get Cookie</h4>
    {{name}}
</body>
</html>
  • The following code is used to set the cookie in views.py which shows the cookie name:
def getcookie(request):
    name = request.COOKIES['name']
    return render(request,'student/getcookie.html',{'name':name})
  • So the output will be:

  • Now, delete the server cookie from your system, and write the following code in views.py
def getcookie(request):
    name = request.COOKIES.get('name')
    return render(request,'student/getcookie.html',{'name':name})
  • Since, there is no cookie in your system, if run the server/get url you should get the output like this:

  • Now, if you want to replace the name of cookie to “Guest” change the code in viewa.py
def getcookie(request):
    name = request.COOKIES.get('name',"Guest")
    return render(request,'student/getcookie.html',{'name':name})
  • The output will be:

  • Now, if you want to add a cookie with the name “seccookie”, make the following changes in views.py of setcookies function:
def setcookie(request):
    response = render(request,'student/setcookie.html')
    response.set_cookie('seccookie', 'Bipasha', expires=datetime.utcnow() + timedelta(days=2))
    return response
  • Now, run the server/set/ and then check the cookies in your system, you should get like this:

  • Hence, we can see a new cookie is added in the server.

Deleting Cookie

  • response.delete_cookie(key, path=’/’,domain=None): This method is used to delete the cookie based on the given key with the same domain and path, if they were set, else the cookie may not be deleted.
  • Let’s set up the delcookie.html file:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Delete Cookie</title>
</head>
<body>
    <h4>Cookie Deleted!!</h4>

</body>
</html>
  • Now, to delete a cookie the function is as follows, define it in views.py
def delcookie(request):
    response = render(request,'student/delcookie.html')
    response.delete_cookie('name')
    return response
  • Now, on running the server/del/we should get like this:

  • On checking the system we will get the cookie deleted. Since we had two cookies one cookie is deleted.

Cookies Security Issues

  • Can misuse Client Details.
  • Can track User.
  • The client can Delete Cookies

Cookies Limitation

  • Each cookie can contain 4096 bytes data.
  • Cookies can be stored in the browser and server.
  • It is sent with each request.