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

如何使用Django的auth.contrib模块通过用户名查询对应用户?

解决方案

你现有代码存在冗余逻辑:你已经配置了IsAuthenticated权限类和JSONWebTokenAuthentication认证类,Django REST Framework会自动完成JWT解码、用户身份校验和对象注入,不需要手动解码JWT拿username查用户,直接调用request.user就能拿到当前请求对应的用户对象,这是最简便的实现方式。

如果你确实需要通过username主动查询auth_user表的用户,正确实现步骤如下:

  1. 先导入Django内置的用户模型:
from django.contrib.auth.models import User
  1. 使用ORM查询对应用户,注意要捕获查询不到的异常:
try:
    user = User.objects.get(username=username)
except User.DoesNotExist:
    raise exceptions.AuthenticationFailed('对应用户不存在')

优化后的接口完整代码参考

class UserProfileView(RetrieveAPIView):
    permission_classes = (IsAuthenticated,)
    authentication_class = JSONWebTokenAuthentication

    def get(self, request):
        # 直接取DRF注入的当前用户,不需要手动解码JWT
        user = request.user
        status_code = status.HTTP_200_OK
        response = {
            'success': 'true',
            'status code': status_code,
            'message': 'User profile fetched successfully',
            'data': {
                'username': user.username,
                'email': user.email,
                'is_superuser': user.is_superuser,
                'last_login': user.last_login
                # 按需返回其他auth_user表的字段即可
            }
        }
        return Response(response, status=status_code)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:36:00