Django: Creating a Custom Middleware Component

Django: Creating a Custom Middleware Component key visual

To create your own custom django Middleware you need to do 4 things

  1. Define a module
  2. Ensure that the module is in the Python path
  3. Load the module in the INSTALLED_APPS section of the settings.py file
  4. Load the middleware in the MIDDLEWARE_CLASSES section of the settings.py file
  5. Add functionality

Define the module

If you dont know how to do this please read this article Django: Defining a Custom Module

Ensure that the module is in the python path

Everything from your "manage.py" file down will automatically be on your python path. 

Load the module

 

Open your settings.py file and find the INSTALLED_APPS section

Add a new entry in the array like below

INSTALLED_APPS = (
    'cms',
    'custom',
)
 

Load the Middleware class

Open your settings.py file and find the MIDDLEWARE_CLASSES section

Add a new entry in the array like below

MIDDLEWARE_CLASSES = (
    'custom.middleware.proxy.PageLikedProxy',
    'django.middleware.common.CommonMiddleware',
)
  • custom/middleware lives next to the manage.py file
  • proxy is the proxy.py file
  • and PageLikedProxy is the name of the class in the proxy.py file

One thing to remember is that the middleware classes are executed in the order that they appear in this array

Add functionality to your middleware

Open the proxy.py file and add the following code

class PageLikedProxy(object):
    def process_request(self, request):
        
        return None

 

For more information about django middleware modules please read the official documentation at Django Middleware

Owen commented:

Very nice post. I just stumbled upon your blog, Thank you for this nice article Thank you for taking time to share it with the readers, I am more than happy to have come across it thanks!and wanted to say that I have really enjoyed browsing your blog posts. cell phones for sale

Deoirt commented:

Everything is very, very clear, open is a description of the problem. It contains the information.<a href="http://www.besthairbase.com/full-lace-wigs">Full lace wigs</a>

Deoirt commented:

Everything is very, very clear, open is a description of the problem. It contains the information.<a href="http://www.besthairbase.com/full-lace-wigs">Full lace wigs</a>

Add a comment

*
*
Your email will not be published
*
*