我试图将所有与业务逻辑相关的验证移动到模型中,而不是将它们留在表单中。但在这里我遇到了一个棘手的情况,为此我想咨询 SO 社区。
在我的 SignupForm(一个模型表单)中,我有以下特定于字段的验证,以确保输入的电子邮件不存在。
def clean_email(self):
email = self.cleaned_data['email']
if ExtendedUser.objects.filter(email=email).exists():
raise ValidationError('This email address already exists.')
return email
如果我将此验证移至模型,根据官方文档,我会将其放入
clean()
对应型号,ExtendedUser
.但该文档还提到了以下内容:Any ValidationError exceptions raised by Model.clean() will be stored in a special key error dictionary key, NON_FIELD_ERRORS, that is used for errors that are tied to the entire model instead of to a specific field
这意味着,使用
clean()
,我无法将由此引发的错误与特定字段相关联。我想知道模型是否提供类似于表单的东西 clean_<fieldname>()
.如果没有,你会把这个验证逻辑放在哪里,为什么?
最佳答案
您可以将清洁方法转换为 validator
并在声明字段时包含它。
另一种选择是将模型字段子类化并覆盖其 clean 方法。
然而,没有定义 clean_<field name>
的直接等价物。方法,就像您可以对表单执行的操作一样。您甚至无法为单个字段分配错误,as you can do for forms
关于django - django 模型是否提供类似于表单的 clean_<fieldname>() 的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9814415/