Django输入验证to_python方法

时间:2018-06-05 20:24:31

标签: python django

当在Django中创建一个字段并调用它的clean方法时,你会看到正在调用一个to_python方法。

https://docs.djangoproject.com/en/2.0/ref/forms/fields/#django.forms.Field.required

为什么只在返回值时调用此(to_python)方法。

def clean(self, value):
    """
    Validate the given value and return its "cleaned" value as an
    appropriate Python object. Raise ValidationError for any errors.
    """
    value = self.to_python(value)
    self.validate(value)
    self.run_validators(value)
    return value


def to_python(self, value):
    return value

1 个答案:

答案 0 :(得分:0)

这是默认实现。方法就在那里,如果你使用更多自定义的东西,比如特殊的字段覆盖,你可以覆盖你的对象如何变成Python值。 Here's the documentation.

它包含一个很好的示例,显示了一个覆盖此方法的类:

def parse_hand(hand_string):
    """Takes a string of cards and splits into a full hand."""
    p1 = re.compile('.{26}')
    p2 = re.compile('..')
    args = [p2.findall(x) for x in p1.findall(hand_string)]
    if len(args) != 4:
        raise ValidationError(_("Invalid input for a Hand instance"))
    return Hand(*args)

class HandField(models.Field):
    # ...

    def from_db_value(self, value, expression, connection):
        if value is None:
           return value
        return parse_hand(value)

    def to_python(self, value):
        if isinstance(value, Hand):
            return value

        if value is None:
            return value

        return parse_hand(value)