Django中request.user在视图不同方法中表现异常的问题求助
Let me break down why this is happening and how to fix it properly.
What's Causing the Issue?
You’re mixing Django’s native view mixins (LoginRequiredMixin, UserPassesTestMixin) with Django REST Framework (DRF) GenericAPIView, which creates a mismatch in how the request is processed:
- Mixin Execution Order: Django runs mixins left to right. Your
LoginRequiredMixinandUserPassesTestMixinexecute before DRF’sGenericAPIViewhandles the request. - Request Object Difference:
- In
test_func(),self.requestis still Django’s nativeHttpRequestobject, which already passed Django’s session authentication (thanks toLoginRequiredMixin), so it shows the authenticated user. - Once DRF’s
GenericAPIViewtakes over, it wraps the native request into a DRF-specificRequestobject. If DRF isn’t configured to recognize Django’s session authentication, this wrapped request defaults toAnonymousUser.
- In
Fix 1: Use DRF's Built-in Permission System (Recommended)
DRF has its own permission framework designed for APIs, so it’s better to replace Django’s mixins entirely. Here’s how:
First, create a custom permission class for the "Poster" group check:
from rest_framework.permissions import BasePermission, IsAuthenticated class IsPoster(BasePermission): def has_permission(self, request, view): # Verify user is authenticated AND part of the Poster group return request.user.groups.filter(name='Poster').exists()
Then update your view to use DRF permissions:
class IndexView(generics.GenericAPIView): serializer_class = IndexSerializer permission_classes = [IsAuthenticated, IsPoster] # DRF-native permissions def get(self, request, *args, **kwargs): print(request.user) # Now shows the authenticated User object return HttpResponse('Welcome')
Fix 2: Fix Authentication Configuration (If You Insist on Django Mixins)
If you want to keep using Django’s mixins, ensure DRF recognizes Django’s session authentication by adding this to your settings.py:
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', # Add other auth classes like TokenAuthentication if needed ] }
This tells DRF to use Django’s session auth to populate the user in its wrapped request. Note this is less idiomatic for DRF APIs, so stick to Fix 1 whenever possible.
Key Takeaway
Django’s native mixins work for server-rendered views, but DRF’s own authentication/permission tools integrate seamlessly with API request handling. Using DRF’s system avoids confusing request object mismatches like this one.
内容的提问来源于stack exchange,提问作者Peter

