Set and Get variables in Django session

Django sessions are very import to maintain variables across multiple web pages or multiple http requests. With session variables we can easily identify users are coming with same session even if they are accessing different web pages of a website. Django session middleware makes developer's life easy and provide easy way to maintain session variables. For using session middleware in a Django web application, we need to first enable session app and session middleware in settings.py. Example is mentioned below


INSTALLED_APPS = [
    'whitenoise.runserver_nostatic',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
After enabling session middleware, we can use session middleware in our Django application (in views and templates). Below is an example we are setting user's information in session after successful login in views.py.

Setting session variables


from django.shortcuts import render

def after_login(request):
    request.session['user_id'] = request.POST.get("user_id")
    request.session['user_name'] = request.POST.get("user_name")
Getting session variables in views.py


from django.shortcuts import render

def check_if_login(request):
    is_loggedin=''
    user_id = request.session.get('user_id')
    user_name = request.session.get('user_name')
    
    if 'user_id' in request.session:
        is_loggedin='yes'
    else:
        is_loggedin='no'
    return render(request, 'user/home.html', {'is_loggedin':is_loggedin})
Getting session variables in template


<html>
<head>
    <title>Session Variable Example</title>
</head>
<body>
    <p>User Name: {{ request.session.user_name }}</p>
</body>
</html>
Deleting a session variable


from django.shortcuts import render

def logout(request):
    request.session.pop('user_id')    
    request.session.pop('user_name')