美文网首页
Django 自定义field

Django 自定义field

作者: noteby | 来源:发表于2020-07-16 11:00 被阅读0次
class ArrayField(forms.Field):
    def __init__(self, min_length=None, max_length=None, *args, **kwargs):
        self.base_type = kwargs.pop('base_type', None)
        self.min_length = min_length
        self.max_length = max_length
        super(ArrayField, self).__init__(*args, **kwargs)

    def validate(self, value):
        super().validate(value)
        if self.min_length:
            if not value or len(value) < self.min_length:
                raise ValidationError("Need at least %s values " % self.min_length)
        if self.max_length:
            if value and len(value) > self.max_length:
                raise ValidationError("Need at most %s values" % self.max_length)

    def base_clean(self, value):
        if self.base_type:
            if isinstance(self.base_type, forms.FileField):
                self.base_type.clean(value)
            else:
                raise ValidationError("Nested field type not error")
        return value

    def clean(self, value):
        try:
            if value in self.empty_values:
                pass
            else:
                value = json.loads(value)
                if not isinstance(value, list):
                    raise ValidationError("Must be array type")
        except json.decoder.JSONDecodeError:
            raise ValidationError("This field is not valid array type")

        value = [self.base_clean(subValue) for subValue in value] if value else []
        return super(ArrayField, self).clean(value)
``

相关文章

网友评论

      本文标题:Django 自定义field

      本文链接:https://www.haomeiwen.com/subject/bxqphktx.html