Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

Django Cookies – Setting up User Cookies in Django

Django Cookies 1

In this article, we talk about setting up Django cookies for our web applications. We’ll begin by discussing the theory and the reason behind the use of cookies and then implement cookies in Django by the end of the article. So let’s get started!

What are Cookies?

Cookies, technically called the HTTP cookies, are a piece of information (stored in a file) that is stored on the client-side browser and is sent to the website server when requested for it.

Since cookies are saved on the client-side, it depends on the client-side security level whether or not it can send those cookies to the webserver. 

It can be stored either permanently or for a specific amount of time. Each cookie has its own expert date and time and is removed automatically from the client’s browser once expired.

How do cookies work?

Http is a stateless protocol which means that a web server cannot distinguish whether you are visiting the page for the first time or whether you have visited previously as well. 

So when you visit a page for the first time, the server responds to the browser with cookies which contains information like the user information generated by the server, etc.

That cookie is stored in your browser. So when you visit again, the cookie-generated earlier is also sent to the server along with the HTTP request. The server can then read the cookie and perform appropriate tasks.

The browser keeps sending the cookies until they get expired and after that are automatically discarded from the browser.

Why are cookies used?

In any eCommerce or social media site like Facebook, you might have observed that if you leave the site without logging out, the next time you go to the site, your account continues to stay logged in. This is done using cookies (which contain user session information)

Similarly, in many eCommerce websites, you get recommendations about different products. Again this because of the cookies storing the search information in your browser.

Hands-On with Django Cookies

We will now see a simple application of cookies and learn how to use them. Django provides a built-in method to use cookies.

1) Django Cookie Attributes

A Django cookie attribute can perform one of two actions. It can drop a cookie in a user’s computer (set) and then access those cookies(get). Let’s look at both the methods here.

Set cookies

This cookie attribute creates a cookie, which is then sent by the server to the user browser to store information. The syntax for set_cookie() is:

set_cookie(cookie_name, value, max_age = None, expires = None) 

Get cookies

This attribute is used by the server to get back the previously sent cookies and read data from it. The syntax to get the cookie is:

request.COOKIES['cookie_Name']

2) Coding the Views

Now that we know the methods that Django cookies can work with let’s set up our views to set those cookies and then access those back. We’ll build up from our Django views article to set up the cookies.

View for sending Cookie

Add the following view into your views.py file

def SetCookie(request):
    response = HttpResponse('Visiting for the first time')
    response.set_cookie('bookname','Sherlock Holmes')
    return response

The URL path will be:

path('setcookie/', SetCookie),

View for getting back the Cookie

Add the following view into your views.py

def GetCookie(request):
    bookname = request.COOKIES['bookname']
    return HttpResponse(f'The book name is: {bookname}')

The URL path will be:

path('getcookie/', GetCookie),

Implementation of cookies

Now that we’ve discussed the individual Views required, Here is the combined script (including both the above section codes) for the Views.py.

Simply add the below code in your views.py along with the URL maps and we are good to go:

from django.shortcuts import HttpResponse

def SetCookie(request):
    response = HttpResponse('Visiting for the first time')
    response.set_cookie('bookname','Sherlock Holmes')
    return response

def GetCookie(request):
    bookname = request.COOKIES['bookname']
    return HttpResponse(f'The book name is: {bookname}')

The urls.py file will look like:

from django.contrib import admin
from django.urls import path
from .views import SetCookie, GetCookie

urlpatterns = [
    path('setcookie/', SendCookie),
    path('getcookie/', GetCookie),
]

That’s it, guys !! Let us now run the server and check !!

Set Cookie
Set Cookie
Get Cookie
Get Cookie

Conclusion

That’s it, guys !! That was all about Django cookies and how you can use them in your projects. Do practice out the codes above yourselves to increase your understanding of cookies.

See you in the next article!! Till then keep coding!!