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.
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.
Url mapping to call both the functions.
And set the session by using localhost:8000/ssession
The session has been set, to check it, use localhost:8000/gsession