Django

Sessions in Django

Sessions in Django

A session is a time when a user interacts with the web application. Sessions are used to store information on the server side. In Django, the sessions are stored automatically in the database. To enable sessions in the Django web application, we need to use the following code:

The code to be used in MIDDLEWARE of settings.py file :  

django.contrib.sessions.middleware.SessionMiddleware 
The code to be used in INSTALLED_APPS of settings.py file :
django.contrib.sessions

The sessions can be set and get with the help of a request.session argument. To understand the concept more clearly, see the example below:

Here, we are going to add functions to set and get session values in our views.py file:

from django.shortcuts import render
from django.http import HttpResponse
def sets(request):
    request.session[‘u-name’] = ‘Ashu Lakhwan’
    request.session[‘u-email’] = ‘ashucool890@gmail.com’
    return HttpResponse(“Session is set successfully.”)
def gets(request):
    username = request.session[‘u-name’]
    usermail = request.session[‘u-email’]
    return HttpResponse(username+ “ “ +usermail);

Next, we are going to do URL mapping to call both the functions in the urls.py file:

from django.contrib import admin
from django.urls import path
from firstapp import views
url_patterns = [
    path(‘admin/’, admin.site.urls),
    path(‘index/’, views.index),
    path(‘sets’, views.setsession),
    path(‘gets’, views.getsession),
]

After running the server using the command ‘$ python3 manage.py runserver’, we need to set the session with the help of the URL below:

http://localhost:8000/sets

And lastly, we need to get the session using the URL:

http://localhost:8000/gets

Top course recommendations for you

    Python Practice Codes
    1 hrs
    Beginner
    8.5K+ Learners
    4.37  (435)
    VLOOKUP in Excel
    1 hrs
    Beginner
    44.8K+ Learners
    4.57  (3373)
    Blockchain Process
    1 hrs
    Beginner
    6.9K+ Learners
    4.56  (578)
    GO Programming Language
    1 hrs
    Beginner
    6.7K+ Learners
    4.48  (510)
    Conditional Formatting in Excel
    1 hrs
    Beginner
    17.4K+ Learners
    4.51  (1637)
    Fibonacci Series in Python
    1 hrs
    Beginner
    2.2K+ Learners
    4.6  (91)
    Design App
    1 hrs
    Beginner
    18.1K+ Learners
    4.44  (1180)
    Pivot Tables in Excel
    1 hrs
    Beginner
    21.4K+ Learners
    4.54  (2301)
    Divide and Conquer Algorithms
    1 hrs
    Beginner
    2.3K+ Learners
    4.57  (332)
    QR Code Generator in Python
    1 hrs
    Beginner
    4.7K+ Learners
    4.36  (210)