I am little bit confused on process_request
and process_view
.
Process request is something that u want to pass on view with request. Example can be taken from request.user
.
Then what does process_view
does ? Is it for executing any view initially befor calling any url ? Like initially I want to show home view but this can be done from url too.
Can anyone give me example when to use process_view
?
Thank you
get_response(request) # Code to be executed for each request/response after # the view is called. return response. The get_response callable provided by Django might be the actual view (if this is the last listed middleware) or it might be the next middleware in the chain.
Middleware is a framework of hooks into Django's request/response processing. It's a light, low-level “plugin” system for globally altering Django's input or output. Each middleware component is responsible for doing some specific function.
Custom middleware in Django is created either as a function style that takes a get_response callable or a class-based style whose call method is used to process requests and responses. It is created inside a file middleware.py . A middleware is activated by adding it to the MIDDLEWARE list in Django settings.
Middleware and decorators are similar and can do the same job. They provide a means of inserting intermediary effects either before or after other effects downstream in the chain/stack.
process_request
is called before Django determines which view should handle the request (hence, it's 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
[...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With