DRF获取当前用户详细信息

DRF获取当前用户详细信息

本文介绍了DRF获取当前用户详细信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取当前登录用户的详细信息:

I want to get the current logged in user's details:

views.py

class UserData(APIView):
    permission_classes = (IsAuthenticatedOrReadOnly,)

    def get(self, request):
        serializer = UserSerializer(self.request.user)
        return Response(serializer.data)

serializers.py

serializers.py

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = CustomUser
        fields = ['id', 'email', 'valid_email', 'nickname', 'name', 'date_of_birth', 'city', 'country', 'date_joined']

当我尝试访问URL时,出现此错误:

When i'm trying to access the url i get this error:

AttributeError at /core/user-data/
Got AttributeError when attempting to get a value for field `email` on serializer `UserSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `AnonymousUser` instance.
Original exception text was: 'AnonymousUser' object has no attribute 'email'.

问题是我已登录.什么可能导致错误?

The thing is that i am logged in. What could cause the error?

推荐答案

在发出此请求时,您似乎没有经过身份验证,这使self.request.user成为AnonymousUser.

It looks like when you are making this request, you are unauthenticated, which makes the self.request.user a AnonymousUser.

您可以尝试通过执行 assert request.user.is_authenticated == True 来验证.它应该返回False.

you can try to verify that by doing assert request.user.is_authenticated==True. It should return False.

这里是 Django AnonymousUser 的链接以及指向 Django身份验证

Here's a link to Django AnonymousUser and a link to Django Authentication

这篇关于DRF获取当前用户详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!