Home >>Django Tutorial >Django Session

Django Session

Django Session

A session is a method to store the information on the server side during the interaction with the web application.

In Django, the session is stored in the database and it also allows the file-based and cache-based sessions. It is implemented by a piece of middleware.

Put the django.contrib.sessions.middleware.SessionMiddleware in MIDDLEWARE and django.contrib.sessions in INSTALLED_APPS of settings.py file.

To set and get the session in views, we can use request.session.

The class backends.base.SessionBase is a base class of all the session objects and It has the following methods:

Method Description
__getitem__(key) It is used to get the session value.
__setitem__(key, value) It is used to set the session value.
__delitem__(key) It is used to delete the session object.
__contains__(key) It is used to check whether the container contains the particular session object or not.
get(key, default=None) It is used to get the session value of any specified key.

Django Session Example

In the given example, the first function is used to set session values and the second is used to get the session values.

//views.py

from django.shortcuts import render  
from django.http import HttpResponse  
  
def setsession(request):  
    request.session['sname'] = 'irfan'  
    request.session['semail'] = 'irfan.sssit@gmail.com'  
    return HttpResponse("session is set")  
def getsession(request):  
    studentname = request.session['sname']  
    studentemail = request.session['semail']  
    return HttpResponse(studentname+" "+studentemail);  

Now we will do the Url mapping to call both the functions.

// urls.py

from django.contrib import admin  
from django.urls import path  
from myapp import views  
urlpatterns = [  
    path('admin/', admin.site.urls),  
    path('index/', views.index),  
    path('ssession',views.setsession),  
    path('gsession',views.getsession)  
]  

Run Server
$ python3 manage.py runserver  

Now we can set the session by using localhost:8000/ssession

The session has been set and we can check it by using localhost:8000/gsession


No Sidebar ads