我正在尝试使用以下序列化程序检索当前登录用户:
@api_view(['GET'])
def current_user(request):
serializer = CurrentProfileSerializer(request.user)
return Response(serializer.data)
这是 CurrentProfileSerializer :
class CurrentProfileSerializer(serializers.ModelSerializer):
user = UserSerializer(required=True)
class Meta:
model = Profile # PROFILE MODEL HAS A ONE-TO-ONE FIELD WITH USER MODEL
fields = '__all__'
depth = 1
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'password')
当我尝试访问current_user
URL 时出现此错误:
尝试获取字段
user
的值时出现AttributeError 序列化器CurrentProfileSerializer
。序列化器字段可能是 命名不正确且与User
上的任何属性或键都不匹配 实例。原始异常文本为:“用户”对象没有属性 “用户”。
答案 0 :(得分:1)
您需要将Profile
实例传递给序列化器,而不是User
。将您的视图更改为此:
@api_view(['GET'])
def current_user(request):
if not request.user.is_authenticated:
return Response('User is not authenticated')
profile = Profile.objects.get(user=request.user)
serializer = CurrentProfileSerializer(profile)
return Response(serializer.data)