【发布时间】:2021-06-18 13:57:59
【问题描述】:
所以,我有这个错误。我使用名为PhoneNumber 的第三方包。现在,当我想序列化我的数据时,我得到了这个错误:Object of type PhoneNumber is not JSON serializable
我可以猜到问题是什么,但不知道如何解决:/ 以前有人遇到过这个/类似的问题吗? :)
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)
【问题讨论】:
标签: django django-rest-framework