我想获取当前登录用户的详细信息:
views.py
class UserData(APIView):
permission_classes = (IsAuthenticatedOrReadOnly,)
def get(self, request):
serializer = UserSerializer(self.request.user)
return Response(serializer.data)
serializers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = CustomUser
fields = ['id', 'email', 'valid_email', 'nickname', 'name', 'date_of_birth', 'city', 'country', 'date_joined']
当我试图访问该网址时,我收到此错误:
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'.
问题是我已登录。什么可能导致错误?
答案 0 :(得分:1)
看起来当你提出这个请求时,你是未经身份验证的,这使得self.request.user成为AnonymousUser。
您可以尝试通过执行assert request.user.is_authenticated==True
来验证这一点。它应该返回False。
这是指向Django AnonymousUser的链接和指向Django Authentication的链接