How to delete session property in Django

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 file as shown below.


In Django, INSTALLED_APPS in the file contains the django.contrib.sessions application, which is used to store sessions in the database.


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 startapp MyApp
delete session property in python django
Set Up Project in Django

Add the app name to the INSTALLED_APP list located in the file, to activate this app.

delete session property using python django

Django includes a 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 = [

Read: Python Django format date

Create Model in Django

To create models in Django open the file inside the app directory and add the below-given code.

from django.db import models

# Create your models here.

class EmployeeLogin(models.Model):
    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 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,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 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 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:
        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 file, and update the DIRS to refer to the Templates folder’s location.

delete session property in python django example
Set path of Django Template

Create a login.html file to add the HTML code for logging the employee, inside the Template folder.

<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
        table {
            border: 8px outset;
            border-radius: 10px;
            border-spacing: 10px;
            padding: 20px;
            margin-left: auto;
            margin-right: auto;

    <h1 align="center">Employee Login</h1>
    <h3 align="center">Please complete the form below to login.</h3>
    {% if messages %}
    {% for message in messages %}
    <div class="alert alert-primary" role="alert">
        <p{% if message.tags %} class="" {% endif %}>{{ message }}</p>
    {% endfor %}
    {% endif %}
    <form method="post">
        {% csrf_token %}
        <div style="text-align:center">
            <button type="submit">Login</button>

  • 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">

    <!-- 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=""
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">


    <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>

        <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">
                    <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                        <a class="dropdown-item" href="">Django</a>
                        <a class="dropdown-item" href="">Matplotlib</a>
                        <a class="dropdown-item" href="">Turtle</a>
                        <a class="dropdown-item" href="">Tkinter</a>
            <a class="btn btn-primary" href="/logout/" role="button">Log Out</a>

    {% if messages %}
    {% for message in messages %}
    <div class="alert alert-primary" role="alert">
        <p{% if message.tags %} class="" {% endif %}>{{ message }}</p>
    {% endfor %}
    {% endif %}
    <div class="container my-3">
        <h1 style="text-align:center;">Welcome to Python Guides</h1>

    <div class="card">
        <div class="card-body">
            <h3 style="text-align:center;">Thanks for landing on this page to know more about</h3>
            <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>
            <h2 style="text-align:center;">Also, Subscribe to Our YouTube Channel for FREE Python Video Tutorials.</h2>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src=""
    <script src=""
    <script src=""

  • 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 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):
    if request.method=='POST':
        if data > 0:
  ,'Session Created')
            return redirect('/dashboard')
  ,'Invalid Credentials')
            print('Not created')
    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'],'Session Deleted')
    return redirect('employee_login')
  • Import the EmployeeLoginForm from the and EmployeeLogin from the 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 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 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 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 createsuperuser

To make a migration file that includes code for a model’s tabular schema type the below command in the terminal.

python makemigrations

To builds tables in accordance with the migration file’s schema execute the below command.

python 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 runserver

By expanding the URL as shown below, we can access the admin panel.

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.

delete session property using python django example
Register employees using the admin interface

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.

deletion of session property in django example
Login username and password

It will be successfully redirected to the dashboard and shows the success message of Django session creation on the top.

deletion of session property in django
Company Management Dashboard

Now, for deletion of the Django session property, we have to click on the Log Out button on the left top.

deletion of session property using django
Log Out Button

It will successfully redirect to the login page and also shows us the message that the Django session property is deleted.

deletion of session property using django example
Delete Session Property in Django

This is how we can delete the Django session property.

Download the delete session property in Django complete code

Here is the code.


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.