Search code examples
djangohttprequestdjango-middleware

Django middleware and HttpRequest change


I have a middleware to make some calculations/check for each incoming request. Some of view need this calculations result.

As I do not want to call the same code twice, I would like to put results to HttpRequest in middleware, so view will be able to read it.

Could you help me with right hint, how can I add an object to HttpRequest?

thanks


Solution

  • HttpRequest is a normal class, you could directly assign the object to its instance, the request, in the middleware. For example:

    class MyMiddleware(object):
        def process_request(self, request):
            request.foo = 'bar'