我实际上正在从文档中复制示例代码,但密码字段“extra_kwargs = {'password':{'write_only':True}}”不会作为验证数据返回。
这是代码:
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserProfile
fields = ('email', 'first_name', 'last_name', 'birthday', 'gender', 'telephone', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = models.UserProfile(
email=validated_data['email'],
first_name=validated_data['first_name'],
last_name=validated_data['last_name'],
birthday=validated_data['birthday'],
gender=validated_data['gender'],
telephone=validated_data['telephone']
)
user.set_password(validated_data['password'])
user.save()
return user
看看局部变量。 “password”传递给初始化函数但不返回validated_data
自:
UserProfileSerializer(data={'email': 'magalhaes@magalhaes.com', 'first_name': 'eduardo', 'last_name': 'magal', 'birthday': None, 'gender': None, 'telephone': '123465', **'password': 123456**}):
email = EmailField(max_length=255, validators=[<UniqueValidator(queryset=UserProfile.objects.all())>])
first_name = CharField(max_length=64)
last_name = CharField(max_length=64)
birthday = DateField(allow_null=True, required=False)
gender = ChoiceField(allow_null=True, choices=(('M', 'Male'), ('F', 'Female'), ('O', 'Outro')), required=False)
telephone = CharField(allow_null=True, max_length=50, required=False)
password = CharField(max_length=128, write_only=True)
validated_data:
{'birthday': None,
'email': 'magalhaes@magalhaes.com',
'first_name': 'eduardo',
'gender': None,
'last_name': 'magal',
'telephone': '123465'} **No password...**
提前致谢!!
答案 0 :(得分:0)
user_serializer = UserProfileSerializer(data=request.data)
if user_serializer.is_valid():
user_serializer.save()
else:
print(user_serializer.errors)
然后你会知道为什么你的密码不是vaild。