Django Set Cookies – Setting up User Cookies in Django

Django Cookies 1

Cookies play an important role in web applications. They allow websites to save small pieces of data on the user’s computer that can be accessed again when the user revisits the site. In Django, it’s simple to set up and work with cookies. 

In this article, we’ll explore how to set, retrieve, and delete cookies in Django. Cookies allow us to build a smooth user experience by remembering users and their preferences. By the end, you’ll be able to use cookies in your own Django projects! 

Introduction to Cookies

Cookies are small pieces of data stored on a user’s computer by the web browser. They are used by websites to store information about the user and their preferences to enhance the user experience.

When a user visits a website, the website can set one or more cookies on the user’s computer. When the same user visits the website again, the website can read the cookies to remember the user and their preferences. This leads to a smoother browsing experience as the website can be customized for the user without asking them to enter the same information again.

Cookies are stored as name-value pairs, e.g. username=John.

They contain a name, value, domain, path, expiration date, and security settings. The domain specifies which websites can access the cookie. The path indicates a URL subset within the domain where the cookie is used. 

Also read: Python Dictionary (Dict) Tutorial

The expiration date determines when the browser should delete the cookie. Security settings control if the cookie should only be transmitted over HTTPS.

There are two main types of cookies: session cookies and persistent cookies. Session cookies are deleted when the user closes the browser, whereas persistent cookies are saved for a long period of time based on the expiration date. Persistent cookies should require user consent according to privacy laws.

Cookies provide many useful features for enhancing web applications and customizing the user experience. However, they also raise some privacy concerns as websites can access personal information stored in cookies. Most browsers allow users to view, modify, and delete cookies to give them more control over their privacy.

Understanding the Role of Cookies

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

Working with Django Set Cookie: Setting and Retrieving Cookies

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

Django Set 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']

Implementing Cookie Handling in Django 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),

Putting It All Together: A Complete Django Set Cookie Example

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

Master Django Set Cookie for Better User Experience

Cookies are powerful tools in any web developer’s toolkit. They allow us to build intelligent, personalized user experiences that feel like magic. In this article, we’ve explored the wonderful world of cookies in Django.

With just a few lines of Python and Django, you can set cookies to remember your users, store their preferences, keep them logged in, and track their activity. Cookies are what power many of the internet’s coolest features!

We’ve seen how to bake cookies (with set_cookie()), access cookies in views, choose between sesion or permanent cookies, and delete cookies when they’re no longer needed. Django makes working with cookies a piece of cake.

Now that you’ve got the recipe for Django cookies, what will you create? A personalized dashboard for your users? A login system? Shopping cart? Product recommendations? The possibilities are endless.