Cookies are used to hold a small piece of information on the client side of the browser. This information gets expired after a specified time and gets removed automatically after it gets expired. In Django, cookies are set and fetched with the help of its built-in methods.
The set_cookie() method in Django is used to set a cookie whereas the get_cookie() method is used to get the cookie. Another method request.COOKIES[‘key’] is an array that is also used to get the cookie.
Example:
We are going to use two functions setcookie() and getcookie() in our views.py file:
from django.shortcuts import render
from django.http import HttpResponse
def setcookie(request):
res = HttpResponse(“Set Cookie”)
res.set_cookie(‘django-tutorial’, ‘greatlearning.com’)
return res
def getcookie(request):
name = request.COOKIES[‘django-tutorial’]
return HttpResponse(“django-tutorial from:” + name
Now, we need to specify URLs to access these functions in our urls.py file:
from django.contrib import admin
from django.urls import path
from firstapp import views
url_patterns = [
path(‘admin/’, admin.site.urls),
path(‘index/’, views.index),
path(‘setcookie’, views.setcookie),
path(‘getcookie’, views.getcookie)
]
Next, we need to start the server before setting the cookie by running the command:
$ python3 manage.py runserver
And after that, the cookie will be set by visiting the URL:
http://localhost:8000/setcookie
This way you can set the cookie and in order to get the cookie, the URL will be: