Django

Cookies Handling in Django

Cookies Handling in Django

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:

http://localhost:8000/getcookie 

Top course recommendations for you

    Arduino vs Raspberry Pi
    2 hrs
    Beginner
    7.7K+ Learners
    4.64  (907)
    Joins in SQL
    2 hrs
    Beginner
    11K+ Learners
    4.4  (720)
    Design Thinking for Beginners
    1 hrs
    Beginner
    15.8K+ Learners
    4.38  (2045)
    Database Management System
    1 hrs
    Beginner
    43.3K+ Learners
    4.39  (6069)
    Become a Web Developer
    1 hrs
    Beginner
    18.2K+ Learners
    4.39  (358)
    .NET Fundamentals
    2 hrs
    Beginner
    24.6K+ Learners
    4.42  (2106)