I have the following middleware:
class TestMiddleware():
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
print(getattr(request, "user", None))
return self.get_response(request)
The print function always prints None. I added the middleware both before and after the django.contrib.auth.middleware.AuthenticationMiddleware line in settings.py, but in either case, I get None. Also, I'm logged in as a user.
What else can I try? I'm using Django 1.11.
Your middleware should be after 'django.contrib.auth.middleware.AuthenticationMiddleware' if you want to access the user. You don't need to use getattr, just request.user should work. Depending on whether you are logged in or not, it will be the logged-in user or an AnonymousUser.