sessions django

Django Sessions

Django Sessions: Django provides full support for anonymous sessions. The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies. Cookies contain a session ID – not the data itself (unless you’re using the cookie-based backend). (official doc)

In simple words, the 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 by adding a piece of code in the middleware.

django.contrib.sessions.middleware.SessionMiddleware

Also, add "django.contrib.sessions" in the INSTALLED_APPS in the settings.py file.

request.session

The request.session is a dictionary that allows you to store and retrieve session data. It accept any object that can be serialized to JSON by default. To set a variable on session we can use request.session like this

request.session['sample_data'] = 1

Now let us consider an example. Add the following code to the views.py file of your app.

    def session_example(self, request):
        request.session["semail"] = "programspeaker@gmail.com"
        s_email = request.session["semail"]
        return HttpResponse("Email from session is:"+ s_email)

We can get a session value by its key. Here we use a key named ‘s_email’ for storing the data and it will raise a key error if the key is not present. To avoid this, we can set a default value if it is not present.

#old line of code
s_email = request.session["semail"]

#new line of code
s_email = request.session.get("semail", "haii")

Now map the following function on the urls.py file

urlpatterns = [  
    path('getsession',views.session_example)  
]  

Now run the server by using the following command

python3 manage.py runserver

Finally, run the URL http://127.0.0.1:8000/getsession in your browser. Then the result is something like shown below.

 Email received from session is:programspeaker@gmail.com  

Share this:

Leave a Comment

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

Scroll to Top