Search code examples
djangodjango-rest-frameworkdjango-users

Django - Retrieve current user


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 serializer CurrentProfileSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'user'.


Solution

  • 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)