代码之家  ›  专栏  ›  技术社区  ›  user1050619

Django输入验证到python方法

  •  -1
  • user1050619  · 技术社区  · 7 年前

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

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

    为什么只返回值时调用这个(topython)方法。

    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 回复  |  直到 7 年前
        1
  •  1
  •   Two-Bit Alchemist    7 年前

    这是默认的实现。方法在那里,因此如果您使用更自定义的东西(如特殊字段重写),您可以重写对象如何转换为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)