Django Session

Session in Django is a mechanism to store small information on the server-side during the interaction with the Django web application. Session information gets stored in the database and allows for cache-based or file-based sessions. Django Session is implemented by the middleware and session app mentioned.

in settings.py namely, django.contrib.sessions.middleware.SessionMiddleware and django.contrib.sessions.

Get and Set Django Session

To set and get the Django session in views, one may use request.session. It is also possible to set the session multiple times.

request.session

The session can also make the client-side stored Cookie data more secure. It can be used to abstract the receiving and sending of cookies, use a session ID for identification, and store data in the database. The session can also make use of the not accept cookies setting in the web browser.

Django Session Example

Mention below code in view.py

from django.shortcuts import render  
from django.http import HttpResponse  
      
def setsession(request):  
        request.session['sname'] = 'Ram'  
        return HttpResponse("User session is set")  
        
def getsession(request):  
        sname = request.session['sname']  
        return HttpResponse("Welcome " + sname);  
                                

On the first visit to the URL response will be:

User session is set

On re-visiting to the URL response will be:

Welcome Ram

Django Session Timeout

To timeout the Django session after a specified timestamp (in seconds) mention the code below in settings.py

SESSION_COOKIE_AGE = 60 # for 60 seconds timestamp                             

To timeout Django session after a specified timestamp (in seconds) of inactivity mention the code below in settings.py

pip install django-session-timeout

    MIDDLEWARE = [
    ...
    'django_session_timeout.middleware.SessionTimeoutMiddleware',
    ...
    ]
                                
    SESSION_EXPIRE_SECONDS = 30
    SESSION_EXPIRE_AFTER_LAST_ACTIVITY = True