【发布时间】:2018-02-28 02:59:55
【问题描述】:
我实际上是从文档中复制示例代码,但密码字段“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
看看局部变量。 “密码”被传递给初始化函数,但不作为验证数据返回
自我:
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)
已验证数据:
{'birthday': None,
'email': 'magalhaes@magalhaes.com',
'first_name': 'eduardo',
'gender': None,
'last_name': 'magal',
'telephone': '123465'} **No password...**
提前致谢!!
【问题讨论】:
-
可以添加 UserProfile 模型吗?
标签: django python-3.x django-rest-framework serialization