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

    GitHub Profile
    1 hrs
    Beginner
    5.8K+ Learners
    4.23  (105)
    Arduino vs Raspberry Pi
    2 hrs
    Beginner
    5.5K+ Learners
    4.56  (291)
    DevOps Landscape
    2 hrs
    Beginner
    2.2K+ Learners
    4.51  (71)
    Joins in SQL
    2 hrs
    Beginner
    8K+ Learners
    4.47  (281)
    Design Thinking for Beginners
    1 hrs
    Beginner
    11.8K+ Learners
    4.41  (781)
    Database Management System
    1 hrs
    Beginner
    29.5K+ Learners
    4.44  (2048)
    Operational Excellence and Critical Thinking
    1 hrs
    Beginner
    5.6K+ Learners
    4.49  (264)
    Become a Web Developer
    1 hrs
    Beginner
    14.4K+ Learners
    4.4  (316)
    .NET Fundamentals
    2 hrs
    Beginner
    19.5K+ Learners
    4.46  (1006)
    .NET OOPS
    1 hrs
    Beginner
    5.2K+ Learners
    4.55  (223)