[Django]-Django REST Framework Object of type PhoneNumber is not JSON serializable

5👍

Try this. It is the most simple solution.

@api_view(['POST', ])
def registration_view(request):

    if request.method == 'POST':
        serializer = RegistrationSerializer(data=request.data)
        data = {}
        if serializer.is_valid():
            ...
            data['phone_number'] = str(account.phone_number)
            ...
        return Response(data)

But i recommend in future projects do this in serializers.py

class RegistrationSerializer(serializers.ModelSerializer):
    ...
    def to_representation(self, instance):
        data = super().to_representation(instance)
        data['response'] = 'successfully registered new user.'
        data['email'] = instance.email
        data['first_name'] = instance.first_name
        data['phone_number'] = str(instance.phone_number)
        data['email'] = instance.email
        data['username'] = instance.username
        data['country'] = instance.country
        return data
👤gardi

Leave a comment