Django 4.0 Custom Middleware Causing 'Too Many Redirects' scenarios
I'm learning this framework and I've been researching this but Quick question that's been bugging me - I'm working on a Django 4.0 application and recently implemented a custom middleware to log request data. However, after adding this middleware, I'm working with a 'Too Many Redirects' behavior when I try to access any page of my application. The middleware is designed to check if the user is authenticated and redirect them to the login page if not. Here's the code for my middleware: ```python class AuthRedirectMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if not request.user.is_authenticated and request.path != '/login/': return redirect('/login/') response = self.get_response(request) return response ``` I've added the middleware in my `settings.py` like this: ```python MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'myapp.middleware.AuthRedirectMiddleware', # My custom middleware ] ``` I also confirmed that the user is actually authenticated but still get redirected to the login page. I suspect it has something to do with how I handle the request path or possibly the order of middleware execution. I've tried logging the values for `request.user.is_authenticated` and `request.path`, and they show the expected results. However, the scenario continues. Has anyone encountered a similar scenario with middleware in Django or can point out what might be going wrong? Any help would be greatly appreciated! Has anyone else encountered this? This issue appeared after updating to Python 3.9. Am I approaching this the right way?