【问题标题】:DRF serializer do not return a value with extra_kwargs of write_onlyDRF 序列化程序不返回带有 write_only 的 extra_kwargs 的值
【发布时间】: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


【解决方案1】:
user_serializer = UserProfileSerializer(data=request.data)
if user_serializer.is_valid():
   user_serializer.save()
else:
   print(user_serializer.errors)

然后你就会知道为什么你的密码无效了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    相关资源
    最近更新 更多