Django Middleware to filter by IP address


First: The path structure

If you don't have it you need to create the middleware folder within your app following the structure:


The folder middleware should be placed in the same folder as, urls, templates...

Important: Don't forget to create the empty file inside the middleware folder so your app recognizes this folder

Instead of having a separate folder containing your middleware classes, it is also possible to put your functions in a single file, yourproject/yourapp/

Second: Create the middleware

Now we should create a file for our custom middleware. In this example let's suppose we want a middleware that filter the users based on their IP address, we create a file called

from django.core.exceptions import PermissionDenied    

class FilterIPMiddleware(object):
    # Check if client IP address is allowed
    def process_request(self, request):
        allowed_ips = ['', '', etc...] # Authorized ip's
        ip = request.META.get('REMOTE_ADDR') # Get client IP address
        if ip not in allowed_ips:
            raise PermissionDenied # If user is not allowed raise Error

       # If IP address is allowed we don't do anything
       return None

Third: Add the middleware in our ''

We need to look for the MIDDLEWARE_CLASSES inside the and there we need to add our middleware (Add it in the last position). It should be like:

     # Above are Django standard middlewares

     # Now we add here our custom middleware

Done! Now every request from every client will call your custom middleware and process your custom code!