Django Session

Session in Django is a mechanism to store small information on server side during the interaction with 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 namely, django.contrib.sessions.middleware.SessionMiddleware and django.contrib.sessions.

Get and Set Django Session

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


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. Session can also make use of not accept cookies setting in the web browser.

Django Session Example

Mention below code in

    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 first visit to the url response will be:

User session is set

On re-visiting to the url response will be:

Welcome Ram