Django ModelViewSet获取当前用户ID报错:AttributeError: module 'request' has no attribute 'user'
Alright, let's fix this error step by step. The AttributeError: module 'request' has no attribute 'user' you're seeing comes down to a common mistake when working with Django REST Framework ViewSets: trying to access the request object at the class level instead of within a method that runs during an active request.
Why Your Code Failed
When you define queryset as a class attribute in your ViewSet, Django initializes this value when the class is loaded—long before any request is made. At that point, request isn't the request instance from the user's call; Python interprets it as an imported module (if you accidentally imported request somewhere) or an undefined variable, hence the error.
Correct Implementation
Instead of defining queryset directly as a class attribute, override the get_queryset() method. This method is called per request, so you'll have access to self.request (the actual request object containing the authenticated user).
Here's the revised code:
from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated from .models import document_type from .serializers import document_typeSerializer class document_typeViewSet(viewsets.ModelViewSet): serializer_class = document_typeSerializer # Add this to ensure only logged-in users can access the view permission_classes = [IsAuthenticated] def get_queryset(self): # Get the current authenticated user from the request current_user = self.request.user # Fetch the user's group (adjust based on your user model setup) # Note: Django's default User model uses a many-to-many `groups` field # If your user has a one-to-one `group` field, use current_user.group instead user_group = current_user.groups.first() # Handle cases where the user has no assigned group if not user_group: return document_type.objects.none() # Filter document_type by the user's group return document_type.objects.filter(role_id=user_group)
Key Notes
- Access
self.requestin methods only: Never try to accessrequestat the class level—this is only valid inside methods that execute during a request (likeget_queryset(),perform_create(), etc.). - Group handling: If your user model uses a one-to-one relationship for groups (instead of Django's default many-to-many
groups), replacecurrent_user.groups.first()withcurrent_user.group. Usingfirst()avoidsMultipleObjectsReturnederrors if a user is in multiple groups. - Authentication: Adding
permission_classes = [IsAuthenticated]ensures anonymous users can't access this view, which prevents errors whereself.request.useris an anonymous user instance.
内容的提问来源于stack exchange,提问作者Ramesh K

