Updated May 2, 2023
Introduction to Django Session
Sessions are server-side cookies. Web applications store user inputs on both the server and client ends. Sessions refer to the data stored on the server end, while cookies refer to the data stored on the client end. These sessions came into play in the Django framework to ensure the application’s security. During these sessions, you will learn how to create, send, and receive cookies. By acknowledging the significance of the stored data, you can effectively tackle different security vulnerabilities by implementing these sessions.
Methods to Catch Session Data in Django
There are three ways to capture and store Django Sessions on the server end.
- Store Sessions onto the connected middleware database.
- Store Sessions onto a file.
- Store Sessions in a temporary cache.
1. Store Sessions onto the connected middleware database
This is the predominant method for catching session data. The below settings need to be inplace for triggering this setup.
Code:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Django_app1',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
2. Store Sessions in a file
The system records and saves sessions to an input file. The server id must have sufficient access specifications for capturing sessions through this technique.
3. Store Sessions in a cache
The cache stores sessions, but if the application or server restarts, it erases all collected session data. However, it is also possible to create persistent cache services to store session data, which will persist even after the application or server restarts.
The parameters below need to be in place for activating the cache-oriented sessions.
Code:
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'
}
}
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Django_app1',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Creating a Session in Django
Given below shows creating a session:
1. SETTINGS.PY changes
We use cache-based session capturing to insert the lines into the SETTINGS.py file.
(SETTINGS.py)
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'
}
}
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Django_app1',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
2. Create a forms.py file in the application
The forms.py file is similar to models.py. All fields used in the form will be declared here under a form class.
(forms.py)
from django import forms
class Valueform(forms.Form):
user = forms.CharField(max_length = 100)
last_name = forms.SlugField()
3. Create a view for the form
In order to create a form view method with Django, you should generate an object for the form class within the views.py file. Afterwards, you can use this object as a value for the context dictionary when rendering the template.
- A post is performed on the rendered page.
- A variable captures the data of the post in the ValueForm class.
- The is_valid() is a mandatory check to verify whether the captured data is valid. The process of validation here will be performed internally by Django. Additionally, if value.is_valid() is not performed, then cleaned_data[] cannot be used.
- The session value of the first name is captured in the below instance.
request_iter.session[first_name] = first_name
- The organization arranges the sessions in a logical manner. If the user inputs the same first name twice, the page redirects to the sessions.
(views.py)
from django.shortcuts import render
from django.http import HttpResponse
from Django_app1.forms import Valueform
def formView(request_iter):
form = Valueform()
if request_iter.method == "POST":
value = Valueform(request_iter.POST)
if value.is_valid():
first_name = value.cleaned_data['first_name']
if request_iter.session.has_key(first_name):
print(request_iter.session.items())
return render(request_iter, 'Session.html' )
else:
request_iter.session[first_name] = first_name
return render(request_iter, 'Form_Handeling.html', {"form":form})
return render(request_iter, 'Form_Handeling.html', {"form":form})
4. Formulate an HTML file for displaying the form
An HTML file needs to be created in the templates directory to display the form; here, the file is template tagged using the below tag,
{{ form.as_p }}
Here “as_p” is used for better designing of the form elements.
{% csrf_token %} line attests to the internal security verification performed by Django.
Example:
Code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Django App1</title>
</head>
<body>
<h1><u> FORMS HANDELING IN DJANGO </u></h1>
<div style = "max-width:470px;">
{{ form.as_p }}
{% csrf_token %}
<input type="submit" class="btnbtn-primary" value="submit">
</div>
</body>
</html>
5. Formulate an HTML file for displaying the page which is triggered when sessions are activated
To create the Session page, you need to generate an HTML file within the templates directory.
Code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Django App1</title>
</head>
<body>
<h1><u> SESSION PAGE IS TRIGGERED </u></h1>
</body>
</html>
6. Tag the view in urls.py file
This is the process of creating a url for the view.
- Import the library from django.conf.urls import url.
- Declare a url entry in the urlpatterns list.
url(url_path, view_to_be_tagged, name_for_this_view)
Code:
from django.contrib import admin
from django.conf.urls import url
from Django_app1 import views
urlpatterns = [
url(r'^$',views.index,name='index'),
url(r'formpage/',views.form_view,name='form'),
url(r'admin/', admin.site.urls), ]
Output:
Attempt 1:
Attempt 2:
Result:
Output Explanation:
Submit your first and last name. If you submit “Rakesh Sharma” again, we will retrieve your session value and activate your session page. Make sure to include “Raviranjan” between these two submissions. Display the most recent snapshot of server-side data on the console once completed. This previous snapshot, we can notice the value of the sessions captured.
The program saves the user’s first name as an individual entry in a dictionary. In each entry, the identified first name serves as both the key and value. When someone enters “Rakesh” for the second time in the first name field, the system will display the session page. This demonstrates how the system gathers and utilizes session data to retrieve and apply previously collected information.
Conclusion
Sessions are always a unique method for increasing the efficiency of the web application. It gives flexibility to the user so that they could much smoothly traverse across the application. Django offers the most sophisticated method for exactly handling these sessions. The above examples show how efficiently cache-based sessions help capture user data for efficient processing.
Recommended Articles
This is a guide to Django Session. Here we discuss the methods to catch session data and create a Django session. You may also have a look at the following articles to learn more –