How to Set and Get Cookie Variables in Django?

Published On: 09/08/2022 | Category: Django


Hi Guys,

Today, I will let you know example of how to set and get cookie variables in django. This tutorial will give you simple example of How can I set and get cookie variable in django. you can understand a concept of how to get cookie value in django. I’m going to show you about set cookie variable in django. follow bellow step for django cookie variables.

So, Cookie has its expiry date and time and removes automatically when gets expire. Django provides built-in methods to set and fetch cookie.

There are ways to set cookie in django. The set_cookie() method is used to set a cookie and get() method is used to get the cookie.

The request.COOKIES['key'] array can also be used to get cookie values.

You can use these examples with django3 (django 3) version.

let's see below simple example with output:

Step 1 : Creating the Views

In this step, we need to create the views for performing set cookies stored in the your local machine.Open the core/views.py file and add.

core/views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse

# Set Cookie Data
def save_cookie_data(request):
    response = HttpResponse("Cookie Set")  
    response.set_cookie('django-tutorial', 'tuts-station.com')  
    return response  

# Get Cookie Data
def access_cookie_data(request):
    tutorial  = request.COOKIES['django-tutorial']  
    return HttpResponse("django tutorials @: "+  tutorial);  

Step 2 : Creating URLs

In this section, we’ll create the urls to access our views.Go to the urls.py core/urls.py file and update it as follows:

core/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('set-cookie/', views.save_cookie_data)
    path('get-cookie/', views.access_cookie_data)
]

Next, we will require the modify the urls.py your root preoject folder lets update the file.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls'),
]
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the address with a web browser.

http://localhost:8000/set-cookie/

I Hope It will help you....