Introduction to Django Cookies
Django is a framework that gives us the option for handling cookies. Cookies provide an option which store and retrieve data which is stored in sessions. These cookies have an expiry date and those are lost after a certain period of time. We already know that, whenever we log in to any web page or application the site default would ask for storing of user id and password, auto-filling of few details with respect to the last logged in sessions are all the work done by cookies. Similarly, we can store our cookies on the client-side and help end-user making their work much easier.
Create Cookies
We can create Django cookie using function set_cookie() and forgetting the response we need to have get() function also.
Syntax:
set_cookie(name, value, max_age=None)
Here, the name would be the name of the cookie set, value is the data that we want to store in the cookie and max is the maximum time limit that cookie has to be expired. This is an optional field, so if no time is set, the cookie would exist till the browser is closed.
How to set Cookie Using Django?
Let us see a small example of how we can manually set up a cookie using Django:
1. view.py
Code:
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return HttpResponse("Welcome")
def setting_cookie(request):
response = HttpResponse("We are setting a cookie")
response.set_cookie('Learning', 'Django',5)
return response
def getting_cookie(request):
first_test = request.COOKIES['Learning']
return HttpResponse("Practice: "+ first_test);
Explanation to the above code: Through the above code, we can observe that for displaying any output to the screen we are using the HttpResponse function. And, for displaying or obtaining the cookie which is set, we are defining it in a different function and then we are using the request function with variable/expression COOKIE added to it. We are henceforth setting a variable with the value of the cookie setting.
2. urls.py
Code:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('setc', views.setting_cookie, name='setc'),
path('getc', views.getting_cookie, name='getc')
]
Explanation to the above code: In the python file urls, we define all the paths that are to be linked with respect to each function that is being written in the views file.
After running the server through the command line: python manage.py runserver
Output:
Getting the Cookie Response:
As highlighted above in views.py code, we had kept the maximum time that cookie has to be saved. Once the time limit is crossed we get the below error:
There is a large description of the error below, please try for yourself and check the total error that has been obtained.
Modify Cookie
Now let us see how we can modify a cookie.
1. view.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return HttpResponse("Welcome")
def setting_cookie(request):
response = HttpResponse("We are setting cookie")
response.set_cookie('Learning', 'Django')
return response
def updating_cookie(request):
response = HttpResponse("We are updating the cookie which is set before")
response.set_cookie(Learning, 'Happy')
return response
def getting_cookie(request):
first_test = request.COOKIES['Stay']
return HttpResponse("Always be: "+ first_test);
We can understand that we have written another function to set up a new cookie value which in turn updated the old one.
2. urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('setc', views.setting_cookie, name='setc'),
path('updc', views.updating_cookie, name='updc'),
path('getc', views.getting_cookie, name='getc')
]
Explanation to the above code: In views.py we have added a new function that is updating our already set cookie. And then in our get function, we are returning the cookie which is set after the updating.
Output1:
Output2:
Output3:
Output4:
If you can observe here the value of the cookie has been updated for the previously set value to the updated value. In this way, we can modify or update the cookie value once set.
Update Django Cookies
We have another way of updating a cookie using the redirect function instead of Httpresponse. But still, we use the set_cookie function only. Below is the code for it, as we added a new function in
view.py
Code:
def updating_cookie1(request):
response = redirect(home)
response.set_cookie('Learning', 'Practising')
return response
Output1:
Output2:
Output3:
Delete Cookie
Here let us get into on how we can delete a cookie that is set.
We already know that there is an optional parameter for the set cookie function called max_age, which would delete the cookie session by default. To make it much simpler, we added the below-mentioned code to the above code.
1. view.py
Code:
def deleting_cookie(request):
response = HttpResponse("We are now finally deleting the cookie which is set")
response.delete_cookie('Learning')
return response
The above code is added in the views file and above the getting_cookie function.
2. urls.py
Code:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('setc', views.setting_cookie, name='setc'),
path('updc', views.updating_cookie, name='updc'),
path('getc', views.getting_cookie, name='getc'),
path('delc', views.deleting_cookie, name='delc')
]
Output1:
Output2:
Output3:
- We even have an attribute name ‘expires’ for handling the end session for a cookie.
- As an exercise try using the expire function and handle deleting a cookie.
- The code can be written as mentioned in the below format:
- response.cookies[‘cookie_name’][‘expires’] = datetime.today() + timedelta(days= number_of_days)
- So, this is how we can delete the cookie.
Enable and Disable Django Cookies
The cookies enable and disable are based on the settings python file. The session variables are present in the settings file which can handle session cookies. The enabling and disabling of cookies are done manually by setting, updating and deleting cookies. There are session-level cookies also, which can be set to true when required. They are set to FALSE by default. These session cookies are encrypted and make sure those are secured. By using different techniques we can use session cookies and update the number of counts whenever a particular website is visited.
Conclusion
Here we have learned on what cookie is and how to handle them. We created Django cookies, updated them and even deleted those cookies. We can have our cookie set with the login user id and password in the same way as many websites are now portraying of. These cookies can help in easy retrieval of data as whenever a user requests for data it does not always go, search in the database and then fetch details for the user. But at the same time, we must be beware of hackers while handling these cookies.