Django Session

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

In Django, by default session stores in the database and also allows file-based and cache based sessions. It is implemented via a piece of middleware and can be enabled by using the following code.

Put 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 and can set multiple times too.

The class backends.base.SessionBase is a base class of all session objects. It contains the following standard methods.

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

Let’s see an example in which we will set and get session values. Two functions are defined in the views.py file.

Django Session Example

The first function is used to set and the second is used to get session values.

//views.py


  1. from django.shortcuts import render  
  2. from django.http import HttpResponse  
  3.   
  4. def setsession(request):  
  5.     request.session['sname'] = 'irfan'  
  6.     request.session['semail'] = '[email protected]'  
  7.     return HttpResponse("session is set")  
  8. def getsession(request):  
  9.     studentname = request.session['sname']  
  10.     studentemail = request.session['semail']  
  11.     return HttpResponse(studentname+" "+studentemail);  

Url mapping to call both the functions.

// urls.py


  1. from django.contrib import admin  
  2. from django.urls import path  
  3. from myapp import views  
  4. urlpatterns = [  
  5.     path('admin/', admin.site.urls),  
  6.     path('index/', views.index),  
  7.     path('ssession',views.setsession),  
  8.     path('gsession',views.getsession)  
  9. ]  

Run Server

$ python3 manage.py runserver  

And set the session by using localhost:8000/ssession

django-session

The session has been set, to check it, use localhost:8000/gsession

django-session 1

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *