In this article, we will discuss How to Create a Session in Django Python, and their role in securing web applications. Sessions provide similar functionality as cookies but are more secure because they store data on the server side rather than on the client side. This article will cover how to set up Django sessions and demonstrate how to use them in a simple web application.
Session in Django
With the session framework in Django, you can save and retrieve any data on a per-visitor basis for your website. This framework stores the data on the server side and handles the sending and receiving of cookies in a simplified way. Essentially, the cookie only contains a session ID rather than the actual data, unless you’re using the cookie-based backend.
Enabling Sessions in Django
We must first enable session middleware in our application before we can create a session in Django. The session middleware is responsible for handling sessions. Middleware is a mechanism to add functionality to Django’s request/response processing pipeline.
To enable session middleware, we need to add the following line to our MIDDLEWARE setting in settings.py:
INSTALLED_APPS = [ 'django.contrib.sessions', ] MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', ]
More Related Articles Find Duplicate Records in Django ORM
Create Session in Django
Creating a session in Django is simple. To save data in the user’s session, we can store the request.session object. Here’s an example.
def setSession(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') try: user = authentication.objects.get(username=username,password=password) if user is not None: request.session['username'] = user.username request.session['emailid'] = user.emailid request.session['userid'] = user.id render(request, 'index.html', {}) except Exception as identifier: messages.error(request, "Invalid login details given") return redirect('/')
Get Django Session Data
In Django, we can simply read from the request.session object to retrieve session data. Here’s an example:
def getSession(request): if 'User_id' in request.session: username = request.session['username']
Delete a Django Session Value
It is important to note that reading from the session does not remove the data from the session. We can use the del keyword to erase data from the session, as shown below.
def logout(request): del request.session['User_id'] return redirect('/')
Conclusion
We’ve covered the fundamentals of session creation in Django Python in this article. We began by talking about what sessions are and how they function in Django. Then we went through how to create and store data in sessions, as well as how to retrieve and delete data from them.