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/ file and add.

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', '')  
    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 core/ file and update it as follows:

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 your root preoject folder lets update the file.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    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 runserver

Next, go to the address with a web browser.


I Hope It will help you....