Django 3 : Creating and getting session variables

Louis SanchezJanuary 20th 2021, 10:15

With Django, storage in a database, generation of the hash code, and exchanges with the client will be transparent. Sessions are stored in the context represented by the request variable. To save a value in a session variable, we must use the following syntax:

request.session['session_var_name'] = "Value"

Once the session variable is registered, you must use the following syntax to recover it:

request.session['session_var_name']

Creating and getting session variables

Step 1 : First, we must define the URL

url ('create-session', 'views.create_session', name="create_session"),
url ('get-session', 'views.get_session', name="get_session"),

Step 2 : We will create our view in the views.py file with the following code:

from django.shortcuts import render
from myproject.models import UserProfile
from django.http import HttpResponse

def create_session(request):
    request.session['favcolor'] = "green"
    return HttpResponse("")

def get_session(request):
    if 'favcolor' in request.session:
        return HttpResponse(request.session['favcolor'])
    else:
        return HttpResponse("")

Step 3 : Typing the http://localhost:8000/create-session URL in our browser.

Step 4 : Typing the http://localhost:8000/get-session URL in our browser.