[Django]-Django middleware difference between process_request and process_view

34👍

process_request is called before Django determines which view should handle the request (hence, its only parameter is the request).

process_view is called after Django determines which view will handle the request, but before that view is called. It will have access to the request object, along with the view that will handle it and the parameters that will be passed to that view.

Whenever you need to know the view that will be used for a request, you can use process_view. A good example for this is Django’s CSRF Middleware process_view, which will not enforce CSRF protection if a csrf_exempt decorator is present on the view the request is meant for:

def process_view(self, request, callback, callback_args, callback_kwargs):
    [...]

    if getattr(callback, 'csrf_exempt', False):
       return None

    [...]

9👍

Adrian Ghiuta have written a very good answer. I just want to add few points to that.

process_request is called before doing the url matching and process_view is called after url matching but before invoking that view.

We can use the process_request to change the url itself and thus invoke a different view. This point helped me understand these, so I thought to answer it, maybe it’ll someone else too.

Leave a comment