So, In this tutorial we will cover following things
- What are Cookies?
- Why are they used on Internet?
- Create Django Cookies
1 What are Cookies?
It is always easy to understand a concept using an example. So, suppose you visited a E-commerce website. Let’s take an example of Amazon. You like some products and add them to cart. After one day you again visited the site, you observed that, the cart is still showing those products. So, how these data are saved, where these data are saved? So, these are data are saved into your browser locally, which are actually set the by visited server(Amazon). Since, http is stateless protocol. When you send a request to a server, the server can’t distinguish whether the user is new or has visited previously. Hence, cookies play a vital role, which is a piece of data stored on a user’s computer by browser while user is browsing.
2 Why are they used for?
Cookies were designed to be a reliable mechanism for websites to remember stateful information (such as items added in the shopping cart in an online store) or to record the user’s browsing activity (including clicking particular buttons, logging in, or recording which pages were visited in the past).
3 Create Django Cookies
1. Create a django project
django-admin startproject myproject
2. Create an app
cd myproject## Create an app
python manage.py startapp cookieapp
3. Add your cookieapp to INSTALLED_APPS in settings.py
4. Create a cookie in Django
Django has method set_cookie() which is used to create a cookie.
The set_cookies() has these attributes
name: It specifies the name of a cookie.
value: It is just value stored in the cookie
max_age: It is the time period of cookie in seconds. After the time period completes, it will expire. It is an optional parameter; if not present then the cookie will exist till the time browser close.
so, here we create a view function setcookie
5 Read a cookie
Using request.COOKIES , we can get the value of a cookie. It accepts the name of the cookie.
You can observe that the name of cookie was ‘localhost’ in line 4. So, we use the name to get the value of a cookie.
urls.py file is created in your cookieapp.
6 Delete a cookie
To delete a cookie we use delete_cookie(). The delete_cookie() takes in the name of the cookie to be deleted, and this method is associated with the response object.
The request.COOKIES is a typically dictionary data type
Since, it is a dictionary, so we can use get() method on dict class
we can also get the value of a cookie using request.COOKIES(‘localhost’,None)
if we find a key exists in the dict then we get the value otherwise it return None.
First time we delete a cookie we get above reponse
Second time We don’t find any cookie named ‘localhost’. Hence, it throws None.
Note : Here is the link of Github repositories. You can find the source code there.