Henrik
Henrik

Reputation: 928

Django REST Framework Object of type PhoneNumber is not JSON serializable

So, I have this error. I use a third party package named PhoneNumber. Now when I want to serialize my data I get this error: Object of type PhoneNumber is not JSON serializable

I can guess what the problem is, but not how to solve it :/ Has anyone had this/similar problem before? :)

serializer.py

from rest_framework import serializers
from phonenumber_field.serializerfields import PhoneNumberField

from user.models import Account



class RegistrationSerializer(serializers.ModelSerializer):

    password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True)
    # country = serializers.ChoiceField(
    #   choices=['US', 'DE', 'FR', 'CH', 'AT', 'GB', 'SE', 'NO', 'FI', 'DK', 'IT', 'ES', 'PT']
    # )
    phone_number = PhoneNumberField()


    class Meta:
        model = Account
        fields = ['phone_number', 'username', 'first_name', 'country', 'email', 'password', 'password2']


        
        extra_kwargs = {
                'password': {'write_only': True},
        }   


    def save(self):

        account = Account(
                    email = self.validated_data['email'],
                    username = self.validated_data['username'],
                    first_name = self.validated_data['first_name'],
                    country = self.validated_data['country'],
                    phone_number = self.validated_data['phone_number'],
                )
        password = self.validated_data['password']
        password2 = self.validated_data['password2']
        if password != password2:
            raise serializers.ValidationError({'password': 'Passwords must match.'})
        account.set_password(password)
        account.save()
        return account

views.py

from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view

from .serializers import RegistrationSerializer


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

    if request.method == 'POST':
        serializer = RegistrationSerializer(data=request.data)
        data = {}
        if serializer.is_valid():
            account = serializer.save()
            data['response'] = 'successfully registered new user.'
            data['email'] = account.email
            data['first_name'] = account.first_name
            data['phone_number'] = account.phone_number
            data['email'] = account.email
            data['username'] = account.username
            data['country'] = account.country
        else:
            data = serializer.errors
        return Response(data)

Upvotes: 4

Views: 4251

Answers (1)

gardi
gardi

Reputation: 111

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

Upvotes: 7

Related Questions