如何使用 Django 的 auth.contrib 模块按用户名查找用户?

How do I lookup a user by username using Django's auth.contrib module?

我将 Django 3.2 与 Django Rest Framework 3.12.2 和 django.contrib.auth 一起使用。我像这样在命令行上创建了几个超级用户

python manage.py createsuperuser --username=joe --email=joe@example.com

这会在迁移自动生成的“auth_user”table 中创建条目。我很好奇如何在使用 django.contrib.auth 方法调用进行身份验证后查找用户。我有这个序列化程序,我用它来登录用户并发出 JWT

class UserLoginSerializer(serializers.Serializer):

    username = serializers.CharField(max_length=255)
    password = serializers.CharField(max_length=128, write_only=True)
    token = serializers.CharField(max_length=255, read_only=True)

    def validate(self, data):
        username = data.get("username", None)
        password = data.get("password", None)
        user = authenticate(username=username, password=password)
        if user is None:
            raise serializers.ValidationError(
                'A user with this email and password is not found.'
            )
        try:
            payload = JWT_PAYLOAD_HANDLER(user)
            jwt_token = JWT_ENCODE_HANDLER(payload)
            update_last_login(None, user)
        except User.DoesNotExist:
            raise serializers.ValidationError(
                'User with given email and password does not exists'
            )
        return {
            'username':user.username,
            'token': jwt_token
        }

我想要一个可以从 auth_user table.

中查找用户信息的端点
class UserProfileView(RetrieveAPIView):

    permission_classes = (IsAuthenticated,)
    authentication_class = JSONWebTokenAuthentication

    def get(self, request):
        try:
            token = get_authorization_header(request).decode('utf-8')
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY)
            username = decoded['username']
                # how to lookup the user at this point?
            status_code = status.HTTP_200_OK
            response = {
                'success': 'true',
                'status code': status_code,
                'message': 'User profile fetched successfully',
                'data': {
                        #...
                    }
                }

检索用户名后,使用 auth.contrib 模块在数据库中查找用户的正确方法是什么?

您可以使用以下代码行获取用户实例

from django.contrib.auth.models import User

User.objects.get(username=username_from_request)

如果您有带有用户名字段的自定义用户模型或配置文件模型,请使用该模型代替 User