Homunculus Reticulli
Homunculus Reticulli

Reputation: 68416

Django computing variable vaue in custom middleware and passing to all view functions

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?

Upvotes: 1

Views: 474

Answers (1)

Selcuk
Selcuk

Reputation: 59184

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

Upvotes: 3

Related Questions