因此,我创建了一个自定义ModelField,扩展了CharField使其具有更好的空字符串验证,并允许我对其进行自定义业务逻辑验证和清理。代码如下:
pdb
因此,想法是,基本上是一个CharField,默认情况下运行我的TextRule对象,但可以重写以运行其他文本类型规则(例如电话号码,电子邮件等),以进行自定义验证和数据清理。 / p>
但是每当我将此字段分配给Model属性时,就会覆盖规则:
class CustomTextField(models.CharField):
10 def __init__(self, *args, rule="TextRule", **kwargs):
11 self.rule = rule
12 super().__init__(args, kwargs)
13
14 def deconstruct(self):
15 name, path, args, kwargs = super().deconstruct()
16 # Only include kwarg if it's not the default
17 if self.rule != "TextRule":
18 kwargs['rule'] = self.rule
19 return name, path, args, kwargs
20
21 def validate(self, value, model_instance):
22 super().validate(value, model_instance)
23 # skip special cases here
24 if self.blank and self.rule == TextRule:
25 return
26 rule_module = __import__("webapp.rules", fromlist=['blah'])
27 class_ = getattr(rule_module, self.rule)
28 rule = class_(value)
29 result = rule.validate()
30 if result != "":
31 raise ValidationError(result)
32
33 def clean(self, value, model_instance):
34 value = super().clean(value, model_instance)
35 rule_module = __import__("webapp.rules", fromlist=['blah'])
36 class_ = getattr(rule_module, self.rule)
37 rule = class_(value)
38 return rule.clean()
django服务器不断向我发送此消息:
zip_code = CustomTextField(rule="ZipCodeRule", max_length=5)
当我尝试运行makemigrations时,也会发生同样的事情。现在完全陷入困境,因为错误中引用的Django源代码不容易理解。