In this Python Django tutorial, I will explain how to delete session property in Django in simple steps.
Recently, I have been creating a Company Management System using the Django web framework. And I have got a requirement for the creation of a session on login of the employee and on logout, it needs to delete session property in Django automatically.
So, I have done the research and created a login and logout page for the company management system that will have a feature of a session deletion property.
Here, we will see:
- What is session
- How to create session in Django
- How to delete session property in Django
- How to create login and logout system in Django
- How to register the employee using Django admin interface
At the end of this article, you can also download the code for deleting sessions in Python Django.
How to delete session property in Django step by step
Django Session
When we are interacting with a web application, a session is a technique for storing data on the server side. Basically, the session is a two-way, semi-permanent interaction between the browser and the server.
In Django, session data is saved in the database and it can be cache-based or file-based sessions.
Enabling Session
In Django, when we created the blueprint of the website, sessions were automatically enabled.
The Django session configurations are set up in the INSTALLED_APPS and MIDDLEWARE sections located inside the settings.py file as shown below.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
In Django, INSTALLED_APPS in the settings.py file contains the django.contrib.sessions application, which is used to store sessions in the database.
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',
]
In Django, for generating unique Session IDs, the middleware.SessionMiddleware is responsible.
Note: When we migrate the application, the django_session table is automatically created in the database.
Read: Python Change Django Version
Delete session property in Django
Now, we will see an example related to the deletion of session property in Django using the login and logout system.
Set up Project in Python Django
To start a Django project, open the terminal and enter the following command. Here, SessionPropertyProject is the name of the Django Project.
django-admin startproject SessionPropertyProject
It will make a folder called SessionPropertyProject and to enter the project, type the below command in the terminal.
cd SessionPropertyProject
Create a Django app named MyApp inside this project folder, by typing the below command in the terminal.
python manage.py startapp MyApp
Add the app name to the INSTALLED_APP list located in the settings.py file, to activate this app.
Django includes a urls.py file in the project directory to map the newly constructed app inside of it, by default. To do so, add the below code in it.
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('MyApp.urls')),
]
Read: Python Django format date
Create Model in Django
To create models in Django open the models.py file inside the app directory and add the below-given code.
from django.db import models
# Create your models here.
class EmployeeLogin(models.Model):
username=models.CharField(max_length=10)
password=models.CharField(max_length=8)
def __str__(self):
return self.username
- Here, we create a model class EmployeeLogin which has the following fields.
- The username and password are Django CharFields. And there is a 10 and 8-character limit for these character fields respectively.
- To change the display name of the object in the Django model use the def __str__(self). It will render the item name as the username as we return the self.username.
Register Model in Admin Interface
To view the model in the admin application, register it on the admin site. Add the following code to the admin.py file by opening it.
from django.contrib import admin
from .models import EmployeeLogin
# Register your models here.
class EmployeeLoginAdmin(admin.ModelAdmin):
list_display = ('username', 'password')
# Model registered with custom admin
admin.site.register(EmployeeLogin,EmployeeLoginAdmin)
- Here, we create the admin class named EmployeeLoginAdmin which displays the field username and password using the list_display tuple.
- Then, we use the admin.site.register function to register the EmployeeLoginAdmin class with EmployeeLogin.
Read: Python Django vs ReactJS
Create Web Form in Python Django using ModelForms
To create a form, add the following code to the forms.py file we created inside the app directory.
from django import forms
from .models import EmployeeLogin
class EmployeeLoginForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
fields='__all__'
model = EmployeeLogin
- Here, we create a form using forms.ModelForm class named EmployeeLoginForm. It has all the fields of the EmployeeLogin model.
- Additionally, we define the widgets attribute PasswordInput that sets the password field as a password input.
Read: Python Django form validation
Login and Logout system template in Django
Create a subdirectory called Templates in the main project directory to store all of the project templates since the front end of a Django application is specified in Templates.
Open the settings.py file, and update the DIRS to refer to the Templates folder’s location.
Create a login.html file to add the HTML code for logging the employee, inside the Template folder.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<style>
table {
border: 8px outset;
border-radius: 10px;
border-spacing: 10px;
padding: 20px;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<h1 align="center">Employee Login</h1>
<hr>
<h3 align="center">Please complete the form below to login.</h3>
<hr>
<br>
{% if messages %}
{% for message in messages %}
<div class="alert alert-primary" role="alert">
<p{% if message.tags %} class="" {% endif %}>{{ message }}</p>
</div>
{% endfor %}
{% endif %}
<form method="post">
{% csrf_token %}
<table>
{{form.as_table}}
</table>
<br><br>
<div style="text-align:center">
<button type="submit">Login</button>
</div>
</form>
</body>
</html>
- First, we set the style of the table in the head tag.
- The heading for the form is then added inside the body tag using the HTML tags h1 and h3.
- To break the line and draw a horizontal line, use br and hr tags respectively.
- To print the error and success message, we use the {{message}} tag in the if and for statement.
- Then, the form tag will be used to post the username and password once it has been submitted with the POST method.
- Next, the csrf_token within the form element is used to shield the form from cyberattacks and enable us to transmit the data securely.
- Then, we use the form.as_table tag to render the form as a table within the table tag.
- Lastly, add a submit button to Login the employee.
Create a home.html file to add the HTML code for showing the dashboard and logout button to the employee, inside the Template folder.
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<title>PythonGuides</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">PythonGuides</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Blogs
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="https://pythonguides.com/django/">Django</a>
<a class="dropdown-item" href="https://pythonguides.com/matplotlib/">Matplotlib</a>
<a class="dropdown-item" href="https://pythonguides.com/turtle/">Turtle</a>
<a class="dropdown-item" href="https://pythonguides.com/tkinter/">Tkinter</a>
</div>
</li>
</ul>
<a class="btn btn-primary" href="/logout/" role="button">Log Out</a>
</div>
</nav>
{% if messages %}
{% for message in messages %}
<div class="alert alert-primary" role="alert">
<p{% if message.tags %} class="" {% endif %}>{{ message }}</p>
</div>
{% endfor %}
{% endif %}
<div class="container my-3">
<h1 style="text-align:center;">Welcome to Python Guides</h1>
</div>
<div class="card">
<div class="card-body">
<h3 style="text-align:center;">Thanks for landing on this page to know more about PythonGuides.com.</h3>
<br>
<h6>I welcome you to the website and hopefully, you got to learn something in Python. I started this website
to share my finding and learnings in Python with you.</h6>
<h6>To keep things simple, I am trying to write a lot of articles on Python. Feel free to give your valuable
comments and also share the articles if you are liking and hoping it will be helpful to someone.</h6>
<br>
<h2 style="text-align:center;">Also, Subscribe to Our YouTube Channel for FREE Python Video Tutorials.</h2>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
</body>
</html>
- To load our CSS, place Bootstrap and jQuery CDN in the head tag before any other stylesheets.
- In the body tag, include the nav tag with the classes navbar and navbar-expand-lg.
- Add a div tag with class collapse navbar-collapse and also add another div with class dropdown-menu to add a dropdown menu bar for adding blog categories.
- Then, we add a div tag with a class card to add the content that we want to show on the website page.
- To print the error and success message, we use the {{message}} tag in the if and for statement.
- Lastly, add a button with a logout link to Log Out to the employee.
Read: Delete Schema from Python Django
Session Property Deletion View
To define the main logic for the deletion of the session property, open the views.py file and add the code given below.
from django.shortcuts import render,redirect
from .forms import EmployeeLoginForm
from .models import EmployeeLogin
from django.contrib import messages
# Create your views here.
# Create Session
def employee_login(request):
message=''
if request.method=='POST':
username=request.POST['username']
password=request.POST['password']
data=EmployeeLogin.objects.filter(username=username,password=password).count()
if data > 0:
request.session['user']=username
messages.info(request,'Session Created')
return redirect('/dashboard')
else:
messages.info(request,'Invalid Credentials')
print('Not created')
form=EmployeeLoginForm()
return render(request,'login.html',{'form':form,'message':message})
# Dashboard
def home(request):
return render(request,'home.html')
# Delete Session Property
def employee_logout(request):
del request.session['user']
messages.info(request,'Session Deleted')
return redirect('employee_login')
- Import the EmployeeLoginForm from the forms.py and EmployeeLogin from the models.py and create a view named employee_login.
- Then, call the if statement and check whether
- If yes, use the request.POST to fetch the username and password.
- After that, we use the filter method with the model object to match up the employee enter username and password with the registered username and password.
Create Django Session
- Use request.session in views to set or create the Django session variable. Basically, it acts like a dictionary i.e. it can define the session name as key and their value as values.
- Here, we use the request object as a request.session[‘user’] session variable and set its value to a username.
- Then, we use message.info to print the success message of session creation.
- If the request method is GET, the user is presented with a blank login page using the render() function.
Render to Dashboard
- Then, we create a function-based view named home to render to the home.html template.
Delete Django Session Property
- Create a view named employee_logout to delete the session property. To delete the session, use the del with the request.session object.
- Then, we use message.info to print the success message of session deletion.
- At last, we use the redirect function to redirect the user to the employee_login view.
Now, we must map the view with the URL in order to call it, thus we must create a file called urls.py in the app directory. Include the code below in it.
from django.urls import path
from . import views
urlpatterns = [
path('', views.employee_login, name='employee_login'),
path('dashboard/', views.home, name='home'),
path('logout/', views.employee_logout, name='employee_logout'),
]
Execute Django Model
To deal with the admin interface, we first have to create the superuser using the below command.
python manage.py createsuperuser
To make a migration file that includes code for a model’s tabular schema type the below command in the terminal.
python manage.py makemigrations
To builds tables in accordance with the migration file’s schema execute the below command.
python manage.py migrate
Register the employee through Admin
Now, to successfully log in to the employee, we have to register it first and for this, we will use the admin interface. Follow the steps below:
Firstly, launch a development server by typing the below-given command in the terminal.
python manage.py runserver
By expanding the URL as shown below, we can access the admin panel.
127.1.1.0/admin
It successfully opens the Django admin, now click on Add option in front of Employee Login and create the new employee by setting Username and Password. Next, click on Save.
Also, check: How to add Google reCAPTCHA to Django Form
Execute the application to delete session property in Django
It successfully opens the Login Page, which looks like this. Fill up the registered username and password of the employee and click on Login.
It will be successfully redirected to the dashboard and shows the success message of Django session creation on the top.
Now, for deletion of the Django session property, we have to click on the Log Out button on the left top.
It will successfully redirect to the login page and also shows us the message that the Django session property is deleted.
This is how we can delete the Django session property.
Download the delete session property in Django complete code
Here is the code.
Conclusion
With this, we have successfully understood how to delete session property in Django. We have also learned about the session and how to create a session in Django.
Additionally, we have also covered the following topics.
- What is session
- How to create session in Django
- How to delete session property in Django
- How to create login and logout system in Django
- How to register the employee using Django admin interface
You may also like to read the following Python Django tutorials.
- Python Django length filter
- How to get data from get request in Django
- Python filter not in Django
- Python Django convert date time to string
- Union operation on models Django
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.