Introduction

In this tutorial we will use custom middleware in our django application.Middleware in Django is a way to process requests and responses globally before they reach the view or after they leave the view. It allows you to add functionalities or perform operations that are applied to every request/response cycle in your Django application. Middleware sits between the web server and the view, intercepting and modifying requests and responses.

Prerequisites:

You need following things to start work:

  1. Python3 installed
  2. Postgresql installed
  3. Django installed

Step 1 — Create a virtual environment to isolate your app dependencies. On windows machine, you can install virtualenv module to create virtual environment and on linux, you can use venv module. I am using venv to create a virtual environment on my linux machine.

  $  python -m venv venv/

Step 2 – A folder named venv will be ceated on the location where you ran above command. Let’s activate the environment:

$  source venv/bin/activate

Step 3 – Now that you are inside your virtual environment, let’s install dependencies that are required for this project:

$  pip install django psycopg2-binary

Django is the framework that you will be using to develop your web app using python and psycopg2-binary is the python module which works as a adapter between postgresql and django.

Step 4 – In this step, you will start a new django project by using following command.

$ django-admin startproject myproject

Step 5- First enter your project directory and start a new django application by following command

$ python manage.py startapp myapp 

In next step we will install djangorestframework to use rest framework in our project

Step 6- Install djangorestframework using this command

$ pip install djangorestframework

Now your project directory should look like this:

Step 7 – To test your application locally, First enter your project directory and run the server using following commands.

$ cd myproject
$ python manage.py runserver

Step 8 – Navigate to http://localhost:8000/ to view the Django welcome screen. It should look like as shown in image:

Alt Text

Kill the server once done by pressing ctrl+z.

Step 9 – Now, you will create a requirements.txt file in your project’s root directory. Use below command to automatically create a requirements.txt and copy all dependencies in it.

  $ pip freeze > requirements.txt

Your project dependencies should have been included in requirements.txt file as shown in image:

Alt Text

Step 10 – Now, Delete the db.sqlite3 file from your project directory as you will use ‘postgres’ database for your django application in next steps

Step 11 – Let’s edit ‘ALLOWED_HOST’ in settings.py file present in myproject directory as shown in image:

For now, You can set ALLOWED_HOST to ‘*’ to let the wsgi allow accepting http request from any domain but in production, this is not recommended.

Step 12 – Let’s edit database connection settings for postgres in settings.py file of django project. First, import os module and change the following lines in settings.py file as shown in image below:

Alt Text

Now add rest framework and our applications in installed apps in settings.py file:

let’s edit settings.py file as shown in below image

Alt Text

Step 13 – Create superuser for your django application using this command:

$ python manage.py createsuperuser

Give all the credentials required :

Open postgres terminal on terminal using this command :

sudo -u postgres psql

Now create databse, host,password and grant all previllages to this user on this database

Add all these credentials along with secret key in .env file as shown below:

Alt Text

Step 14 – Now create models in model.py file present in myapp directory with desired field But one thing is we have to keep one foreign key in dependent models

Alt Text

Step 15 Now add a new file with name middleware.py in Application directory :

Alt Text

Alt Text

Step 16 – Let’s add a new file with name serializers.py in our application directory and create modelserializers for each model to receive post request data as shown in below image:

Alt Text

Step 17 – Create views according to your requirement.As we are using signals so we don’t need create view for dependent models so we will use only RetrieveUpdateView from generic views:

Alt Text

Alt Text

Alt Text

Step 18 – Add urls.py file to application directry and add url paths for each view in this file as shown below :

Alt Text

Step 19 – Include application url paths in your project urls.py file as shown in below image:

Alt Text

Now start you development server using command :

$ python manage.py runserver

Now check url and add this address to postman to call post request for user login if it’s working fine than your custom middleware is working

Check the response on your teminal after calling any Api on postman

If everthing is working fine then you will see all the print statements on your terminal

Alt Text

Alt Text

To confirm complete working remove localhost ip address from Allowed Hosts like shown in below Image:

Alt Text

After that Call Same Api on postman than it will show bad request error or Forbidden error As shown in below image :

Alt Text

Thankyou,you have successfully create custom middlewares to track requests and responses and preventing Api access from unauthorized Ip addresses