自定义字段不返回值

时间:2017-04-16 08:28:46

标签: django django-models

在Django项目中,我需要使用GTIN,然后我创建了一个基本的自定义字段,如下所示:

class GTINField(models.CharField):
    description = _("GTIN Code")
    default_error_messages = {
        'blank': _('GTIN code is required.'),
        'invalid': _('Enter a valid GTIN code.'),
    }
    empty_strings_allowed = False
    default_validators = [validate_gtin]

    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 14
        super(GTINField, self).__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super(GTINField, self).deconstruct()
        del kwargs["max_length"]
        return name, path, args, kwargs

验证器是:

@deconstructible
class GTINValidator:
    message = _('Enter a valid gtin code.')
    code = 'invalid'

    def __call__(self, value):
        if not self._is_valid_code(value):
            raise ValidationError(self.message, code=self.code)

    def _is_valid_code(self, code):
        if not code.isdigit():
            return False
        elif len(code) not in (8, 12, 13, 14):
            return False
        else:
            return int(code[-1]) == self._get_gtin_checksum(code[:-1])

    def _get_gtin_checksum(self, code):
        total = 0

        for (i, c) in enumerate(code):
            if i % 2 == 1:
                total = total + int(c)
            else:
                total = total + (3 * int(c))

        check_digit = (10 - (total % 10)) % 10
        return check_digit


validate_gtin = GTINValidator()

现在,我想在clean()方法中格式化我的字段(在字符串中删除“ - ”)但是我无法获取字段值,Pdb总是返回

(Pdb) self.ean
<gtinfield.fields.GTINField>

我是否遗漏了the doc的内容?

0 个答案:

没有答案