You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django ModelViewSet获取当前用户ID报错:AttributeError: module 'request' has no attribute 'user'

Fixing AttributeError: module 'request' has no attribute 'user' in Django ViewSet

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.request in methods only: Never try to access request at the class level—this is only valid inside methods that execute during a request (like get_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), replace current_user.groups.first() with current_user.group. Using first() avoids MultipleObjectsReturned errors if a user is in multiple groups.
  • Authentication: Adding permission_classes = [IsAuthenticated] ensures anonymous users can't access this view, which prevents errors where self.request.user is an anonymous user instance.

内容的提问来源于stack exchange,提问作者Ramesh K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:37:28