Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

Django Sessions – Setting up User Sessions with Django

Django Sessions

In this article, we’re talking about Django sessions. Sessions behave and provide us with similar results as with using cookies. But saving cookies on the client-side can lead to security threats. Hence to make the process more secure, we use sessions. This is exactly what we will learn in this article – How to secure our websites from unsafe cookies using Django sessions!!

What are Django Sessions?

As we know from the Django cookies article, we can use cookies saved on the client-side, to store various useful data for the Web Apps. 

But storing information related to Web App on the client-side can lead to so many security issues and hence is not a good idea to save on the client’s side. Some of the possible threats are:

  1. Hackers can modify the cookie data and send them to harm our website potentially.
  2. We can’t store sensitive data like user passwords etc. in cookies.
  3. We can only store a limited amount of data in cookies. Most of the browsers don’t allow more than 4kb of data.

To tackle all these issues, we use sessions, which is a mechanism to store the cookies on the server-side itself. Therefore all the data are stored in the server as a DB Table, and the client-side cookie just has the session ID for identification.

Hence with sessions, we can save sensitive data, and with sessions, we can deal with the no cookie policy of the Client browsers as well.

The Django has a session framework pre-built in its framework. Let us now know about it.

How to Set Up Django sessions?

The session attribute is present as a dictionary in the request data. Hence the syntax we use to call a session is:

request.session.(#other_commands)

1) Setting up sessions

Setting up a session means that we:

  1. create a session
  2. then send the session ID as a cookie to the client.

The syntax to set session is:

request.session['session_name'] = 'session_value'

2) Accessing sessions

To get back the session information, we call the get session attribute. Which then performs the following task:

  1. Receives a cookie from the client
  2. reads the cookie for the session ID
  3. Retrieves the session data using the Session ID

The syntax to get session is:

#method1
session_value = request.session.get('session_name') 

#method2
session_value = request.session['session_name']

3) Other Session attributes

Apart from this, there are certain other session functions as well. Some of them are given below:

  • set_expiry(value): Sets the expiration time for the session.
  • clear)_expired(): Removes the expired sessions
  • get_expiry_age(): Returns the number of seconds left untill the session expires
  • get_expiry_date(): Returns the expiry date of the session

Enough with the reading part right!! Let us now get our hands dirty in it.

Hands-on with Django Sessions

We will now build a simple web application that sets the session using one View and then gets back the session using another.

1) Coding the SetSession View

Add the following SetSession View in the views.py

def SetSession(request):
    request.session['book_name'] = 'Sherlock Holmes'
    return HttpResponse('The Session has been successfully set')

The URL path of the view will be:

path('setsession/',SetSession),

2) Coding the GetSession View

Now below the SetSession, add the following GetSession View in the views.py

def GetSession(request):
    book_name = request.session.get('book_name')
    return HttpResponse(f'The Book Name is: {book_name}')

The URL path of the view will be:

path('getsession/',GetSession),

Implementation of the Code

Now that we’ve discussed the individual Views required, Here is the combined script (including both the above section codes) for the Views.py

Simply add the below code in your views.py along with the URL maps and we are good to go:

from django.shortcuts import HttpResponse

def SetSession(request):
    request.session['book_name'] = 'Sherlock Holmes'
    return HttpResponse('The Session has been successfully set')

def GetSession(request):
    book_name = request.session.get('book_name')
    return HttpResponse(f'The Book Name is: {book_name}')

The final urls.py file will look like:

from django.contrib import admin
from django.urls import path
from .views import SetSession, GetSession
 
urlpatterns = [
    path('setsession/',SetSession),
    path('getsession/',GetSession),
]

That’s it, let us now fire up the server and go to 127.0.0.1:8000/setsession/

Set Session
Set Session

We have set the session successfully.

Let us now get it back through the 127.0.0.1:8000/getsession/ endpoint.

Get Session
Get Session

That’s it !! see how simple it is to use the sessions.

Conclusion

That’s it, guys !! That was all about Django sessions and how you can use them in your projects. Do check out the Django Cookies article for information about Cookie handling.

See you in the next article!! Till then, keep coding!!