pass variable from custom middleware to views

I have a custom middleware :

class CustomMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        print("Middleware: Custom code is running!")

        # Code to run before the view is called
        request.foo = "bar"

In my views.py :

def add(request, customer_id):

    print("request.foo in add function = ", request.foo)

But it always outputs AttributeError: 'WSGIRequest' object has no attribute 'foo'

EDIT : I found that my custom middleware is being run after add.

I think you miss the last two lines in your custom middleware __call__ method

class CustomMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        print("Middleware: Custom code is running!")

      response = self.get_response(request)    # this line
      # Code to be executed for each request/response after
      # the view is called.
      # Code to run before the view is called
      request.foo = "bar"
      return response           # this line

It will work as expected (if you have the right configurations in your settings.py file)

Please take a look here Django Middleware Docs

Hope this helps

I missed this - now it’s working but

response = self.get_response(request)

Oddest thing ever :
How is this running properly with no errors on the webpage, yet on console it throws but at the same time its printing the correct values in both functions ?

Middleware: Custom code is running!
Internal Server Error: /add
Traceback (most recent call last):
  File "D:\workspace\django\project-007\env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "D:\workspace\django\project-007\env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\workspace\django\project-007\env\lib\site-packages\ms_identity_web\__init__.py", line 290, in assert_login
    return f(*args, **kwargs)
  File "D:\workspace\django\project-007\application\views.py", line 49, in add
    print("request.foo in add = ", request.foo)
AttributeError: 'WSGIRequest' object has no attribute 'foo'
request.foo in custom_middleware = bar
request.foo in add =  bar

Are you sure you have the next two lines now in the __call__ method

      response = self.get_response(request)    # this line
      return response           # this line

If you are sure then you have another thing in your add() function in your views.py file (recheck) or share your views with us

By the way your custom middleware class CustomMiddleware: works as expected on my project without any errors

Try to make it like this

class CustomMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        print("Middleware: Custom code is running!")
        # Code to run before the view is called
        request.foo = "bar"
        
        # 
        response = self.get_response(request) # 
        return response  #

Instead of this

class CustomMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        print("Middleware: Custom code is running!")        
        response = self.get_response(request) 

        # Code to run before the view is called
        request.foo = "bar"
        return response  #

The first one works as expected but the second one print ( “Middleware: Custom code is running!” ) and then give error
AttributeError: 'WSGIRequest' object has no attribute 'foo'

This is how my custom middleware class is :

class CustomMiddleware:

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):

        print("Middleware: Custom code is running!")

        # Code to run before the view is called
        response = self.get_response(request)
        # Code to run after the view is called and before the response is returned

        azureAD = getAzureADDetails(request)
        
        if len(azureAD) > 0:

            claims = request.identity_context_data._id_token_claims

            try:
                application_user = User.objects.get(email=claims['preferred_username'])
                request.user = application_user
                request.userid = request.user.id
                response = self.get_response(request)
            except User.DoesNotExist:
                print("not able to find from users table")


        return response

My views.py :

@ms_identity_web.login_required
def add(request, customer_id):

    print("request.user in add =", request.user)

    userid = -1

    try:
        userid = request.userid
        print("request.userid in add =", request.userid)
    except Exception as e:
        print("request.userid not found in add")

Now there are 0 errors though I don’t know how this getting called twice :

Middleware: Custom code is running!
request.user in add = AnonymousUser
request.userid not found in add
request.user in add = AnonymousUser
request.userid in add = 149