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 settings.py.

settings.py
MIDDLEWARE = [
    ...
    'django.contrib.sessions.middleware.SessionMiddleware',
    ...
]

...
INSTALLED_APPS = [
    'django.contrib.sessions',
]
...

So, run python manage.py 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/views.py file and add.

core/views.py
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'] = 'tuts-station.com'
    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 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-session/', views.save_session_data)
    path('get-session/', views.access_session_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-session/

I Hope It will help you....