Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"Got KeyError when attempting to get a value for field `username` on serializer `UserSerializer`

trying to get current user but it shows username keyerror but everything’s all good from my side. Can anyone say whats the error?

views :

@api_view(['POST'])
def register(request):
data = request.data

user = SignUpSerializer(data=data)
if user.is_valid():

    if not User.objects.filter(username = data['email']).exists():

        user = User.objects.create(
            first_name = data['first_name'],
            last_name = data['last_name'],
            username = data['email'],
            email = data['email'],
            password = make_password(data['password'])
        )
        return Response({
            'details':'Sucessfully registered.'
        }, status.HTTP_201_CREATED)
    else:
        return Response({
            'error':'User already exists.'
        }, status.HTTP_400_BAD_REQUEST)
else:
    return Response(user.errors)

here is UserSerializer views.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def current_user(request):
    user = UserSerializer(request.data)
    print(user)
    return Response(user.data)

Serializers.py :

class SignUpSerializer(serializers.ModelSerializer):

class Meta:
    model = User
    fields = ('first_name', 'last_name', 'email', 'password')

    extra_kwargs = {
        'first_name':{'required':True, 'allow_blank':False},
        'last_name':{'required':True, 'allow_blank':False},
        'email':{'required':True, 'allow_blank':False},
        'password':{'required':True, 'allow_blank':False, 'min_length':4}
    }

This is user serializer

class UserSerializer(serializers.ModelSerializer):

class Meta:
    model = User
    fields = ('first_name', 'last_name', 'email', 'username')

enter image description here

>Solution :

Use this instead. Replace request.data with request.user

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def current_user(request):
user = UserSerializer(request.user)
print(user)
return Response(user.data)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading