How to Set and Get Session Variables in Django?

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

Hi Guys,

Now, let's see tutorial of how to set and get session variables in django. This article goes in detailed on How can I set and get session variable in django. you can understand a concept of how to get session value in django. you'll learn set session variable in django. Let's see bellow example django session variables.

Sessions are basically use, the data is not stored directly in the browser. Instead, it is stored in the server.

The Django creates a unique 32-character-long random string called a session key and associates it with the session data.

The server then sends a cookie named sessionid, containing the session key, as value to the browser.

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

let's see below simple example with output:

Step 1 : Session Configuration

In this step, we’ll configuration a django session in django middleware we need to add two things in our


So, run python migrate to populate the table. The table has three columns: session_key, session_data, and expire_date as well generate in database.

Step 2 : Creating the Views

In this step, we need to create the views for performing set session stored in the server.Open the core/ file and add.

from django.shortcuts import render, redirect
from django.http import HttpResponse

# Set Session Data
def save_session_data(request):
    request.session['user_id'] = 1
    request.session['site'] = ''
    return HttpResponse("Session Data Saved")

# Get Session Data
def access_session_data(request):
    response = ""
    if request.session.get('user_id'):
        user_id = request.session.get('user_id')
        response += "User Id : {0} 
".format(user_id) if request.session.get('site'): site = request.session.get('site') response += "Welcome to : {0}
".format(site) if not response: return HttpResponse("No session data") else: return HttpResponse(response)
Step 6 : 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-session/', views.save_session_data)
    path('get-session/', views.access_session_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....