DRF如何在序列化器字段中添加验证错误?

时间:2019-03-06 12:23:49

标签: django django-rest-framework

在下面的示例中,所有字段均为必填字段。电话为空且密码不匹配的发帖请求只会导致不匹配的错误-大概是因为电话按字母顺序排序是后来出现的。

您如何向序列化器字段中添加错误而不是覆盖它们?

 IN: curl -X POST http://localhost:8000/register/ -d "password=not&password1=matching"

OUT: {"password1":["Passwords do not match."]}

class UserRegistrationSerializer(serializers.ModelSerializer):
    password1 = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ('password', 'password1', 'phone')
        extra_kwargs = {
            'password': {'write_only': True},
            'password1': {'write_only': True},
            'phone': {'required': True},
        }

    def create(self, validated_data):
        del validated_data['password1']
        password = validated_data.pop('password', None)
        instance = self.Meta.model(**validated_data)
        if password:
            instance.set_password(password)
        instance.save()
        return instance

    def validate(self, attrs):
        if attrs.get('password') != attrs.get('password1'):
            raise serializers.ValidationError({'password1': ['Passwords do not match.']})
        return attrs

理想情况下,curl请求将输出{"password1":["Passwords do not match."],"phone":["This field is required."]}

0 个答案:

没有答案