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

Django类视图加认证装饰器后request.user.username仍为空的问题

Django类视图认证后request.user为空的解决方法

你直接给类视图的get方法加@api_view和@authentication_classes是无效的——这些装饰器是为函数视图设计的,类视图的认证逻辑有专门的配置方式。原因是类视图的请求处理通过dispatch方法统一分发,认证步骤在dispatch阶段执行,直接给get方法加装饰器不会触发认证流程,自然request.user为空。

以下是正确的解决方式:

方法1:用装饰器修饰整个类

确保你的XyzView继承自Django REST Framework的APIView,然后在类上添加认证和权限装饰器:

from rest_framework.views import APIView
from rest_framework.decorators import authentication_classes, permission_classes
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

@authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated])
class XyzView(APIView):
    def get(self, request):
        # 此时request.user已被正确填充
        print(request.user.username)
        return Response({"message": "success"})

方法2:在类内部设置属性

无需装饰器,直接在类中定义authentication_classes和permission_classes属性,效果与上述一致:

from rest_framework.views import APIView
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

class XyzView(APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        print(request.user.username)
        return Response({"message": "success"})

关键注意点

  • 必须确保XyzView继承自DRF的APIView(或其派生类,比如ListAPIView、RetrieveAPIView等),而非Django原生的View——原生View不支持DRF的认证流程。
  • 如果类视图需要开放部分权限(比如允许匿名访问但认证后获取用户信息),可将permission_classes设为[AllowAny],这样无token也能访问,有token时request.user会被正确填充。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 16:07:49