1

I am using Django 3.2. I want to compute the value of variable and make that value available to all views in my project.

I have decided to use middleware - but it is not clear (yet), how I can make the value I computed in MyCustomMiddleware available in a view.

Here is my custom middleware class:

class MyCustomMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.
        mysecret_value = 4269  

        return response

After making the requisite modifications to the MIDDLEWARE section in settings.py, how do I acesss mysecret_value in my views?

myapp/views.py

def foobar(request):
    the_value = mysecret_value # <- how do I access the RHS variable?
Homunculus Reticulli
  • 65,167
  • 81
  • 216
  • 341
  • https://stackoverflow.com/questions/56632988/add-a-custom-header-on-request-in-a-django-middleware – token Apr 28 '21 at 06:37
  • I know you asked for access in the view, but just in case what you actually need is to have it in the template, what you want is a `context_processor` not a new middleware. – michjnich Apr 28 '21 at 07:03

1 Answers1

3

Middlewares run before views, so you can actually modify the request object:

class MyCustomMiddleware:
    ...
    def __call__(self, request):
        request.mysecret_value = 4269
        return self.get_response(request)

Then you can access this value from any view:

def foobar(request):
    the_value = request.mysecret_value
Selcuk
  • 57,004
  • 12
  • 102
  • 110