I am trying to retrieve the current logged in user using the following serializer:
@api_view(['GET'])
def current_user(request):
serializer = CurrentProfileSerializer(request.user)
return Response(serializer.data)
And this is the 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')
I am getting this Error when I am trying to go to the current_user
URL:
Got AttributeError when attempting to get a value for field
user
on serializerCurrentProfileSerializer
. The serializer field might be named incorrectly and not match any attribute or key on theUser
instance. Original exception text was: 'User' object has no attribute 'user'.
You need to pass Profile
instance to serializer, not User
. Change your view to this:
@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)