django rest 框架验证和刷新数据

django rest framework validation & refreshing data

我正在尝试验证 password1、password2 是否匹配,而不是使用对象级验证,因为它是在所有字段级验证之后执行的,但是 validate_field 只接受一个值。如何在休息框架中实施以下内容?

def validate_password2(self, data):
        print 'validating...'
        password1, password2 = data['password1'], data['password2']           
        if password1 and password2 and password1 != password2: 
              raise serializers.ValidationError('The two passwords do not match.')         
        return password2

并且当发生错误时,表格中的数据被清除。即使出现像 django form.fields?

这样的错误,我如何保留输入数据

像这样在 DRF 中验证密码

def validate_password2(self, attrs, source):
    """
    password_confirmation check
    """
    password_confirmation = attrs[source]
    password = attrs['password1']

    if password_confirmation != password:
        raise serializers.ValidationError('password didnot match')

    return attrs

不要添加字段级验证,而是将此检查添加到对象级验证,因为您需要访问多个字段。

甚至 DRF 文档也定义了这一点:

Object-level validation

To do any other validation that requires access to multiple fields, add a method called .validate() to your Serializer subclass. This method takes a single argument, which is a dictionary of field values. It should raise a ValidationError if necessary, or just return the validated values.

您只需执行以下操作:

def validate(self, data):
    ...
    password1 = data['password1']
    password2 = data['password2']
    if password1 and password2 and password1 != password2:
        raise serializers.ValidationError('The two passwords do not match.')
    ....
    return data

还可以在发生错误时访问初始数据,您可以使用 your_serializer.initial_data