Django.fun

auth_middleware.<locals>.middleware() got an unexpected keyword argument 'user_id'

I am trying to apply my custom auth middleware in the url path that has id .

But getting this error.

from .views import Profile

app_name = 'account'

from employer.middlewares.auth import auth_middleware

urlpatterns =[
    path('dashboard/pages-profile/<int:user_id>', auth_middleware(Profile.as_view()), name='profile'),
    ]

And my auth middleware is this:

from django.http import HttpResponseRedirect

def auth_middleware(get_response):
    def middleware(request):
        return_url = request.META['PATH_INFO']
        if not request.session.get('user_id'):
            return HttpResponseRedirect(f'{reverse("account:login")}?return_url={return_url}')
        response = get_response(request)
        return response
    return middleware

Answers: 1

Answered by Razenstein, Nov. 25, 2021, 9:34 a.m.

You need to hook your custom middleware into the chain of middleware defined in MIDDLEWARE in your settings.py. The path statement where you currently just place it expects a function or Class based view. So you try to activate your middleware by just kind of wrapping the view in the path statement which is not correct. Se also the explanations when you look for "custom middleware tutorial" in the django docs.