Updated May 4, 2023
Introduction to Django Cookies
Django is a framework that gives us the option for handling cookies. Cookies offer an option to store and retrieve data within sessions. They possess an expiry date and expire after a specific period, resulting in data loss. We know that whenever we log in to any web page or application, the site default asks for storing the user ID and password, and cookies are responsible for performing tasks such as auto-filling specific details based on the last logged-in sessions. Similarly, we can store our cookies on the client side and help end-user make their work much easier.
We can create a Django cookie using the function set_cookie() and forgetting the response. We need to have a get() function also.
set_cookie(name, value, max_age=None)
Here, the name would be the name of the cookie set, the value is the data we want to store in the cookie, and max is the maximum time limit for the cookie to expire. If you do not specify a specific time, your browser will retain the cookie until you close it. This is an optional field.
How to Set Cookie Using Django?
Let us see a small example of how we can manually set up a cookie using Django:
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: Through the above code, we can observe that we are using the HttpResponse function to display any output to the screen. We define a separate function to display or obtain a set cookie and then include the variable/expression COOKIE in the request function. We are henceforth setting a variable with the value of the cookie setting.
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: In the Python file urls, we define all the paths to be linked with respect to each function being written in the views file.
After running the server through the command line: python manage.py runserver
Getting the Cookie Response:
As highlighted above in the 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 it yourself and check the total error obtained.
Now let us see how we can modify a cookie.
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 understand that we have written another function to set up a new cookie value that updated the old one.
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: In views.py, we have added a new function updating our already set cookie. And then, in our get function, we return the cookie, which is set after the update.
As you can observe here, the value of the cookie has been updated from the previously set value to the updated value. 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 an HTTP response. But still, we use the set_cookie function only. Below is the code for it, as we added a new function in
def updating_cookie1(request): response = redirect(home) response.set_cookie('Learning', 'Practising') return response
Here let us get into how we can delete a set cookie.
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 simplify it, we added the code below to the above 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.
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') ]
- We even have an attribute name ‘expires’ for handling the end session for a cookie.
- Try using the expire function and handle deleting a cookie as an exercise.
- You can write the code in the following 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 enabled, and disabled are based on the settings python file. The session variables are present in the settings file, which can handle session cookies. Manually setting, updating, and deleting cookies enables and disables their functionality. Users can manually activate session-level cookies by setting them to “true” when needed, although their default state is set to “false.” The functionality allowing this customization is implemented through encrypted session cookies, ensuring enhanced security. Through the implementation of various techniques, session cookies can be employed to track and update the visit count whenever a particular website is visited.
Here we have learned 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 many websites now portray. These cookies can help in the 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.
We hope that this EDUCBA information on “Django Cookies” was beneficial to you. You can view EDUCBA’s recommended articles for more information.