我不确定我的答案。但是,我们假设您正在使用field1
数据以便生成field2
价值。您可以使用自定义方法生成它并将其分配给__init__
方法。这将为您提供稍后清理这两个字段的好方法。
class MyModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
# now lets generate field2 data using field1 data..
self.data['field2'] = self.field[1] * 154220
class Meta:
widgets = {'field2': forms.HiddenInput()}
def clean_field1(self):
## Here you can do validation for field1 only.
## Do it like field2 is not exisited.
def clean_field2(self):
## Here you can do validation for field2 only.
## Do it like field1 is not exisited.
def clean(self):
"""
In here you can validate the two fields
raise ValidationError if you see anything goes wrong.
for example if you want to make sure that field1 != field2
"""
field1 = self.cleaned_data['field1']
field2 = self.cleaned_data['field2']
if field1 == field2:
raise ValidationError("The error message that will not tell the user that field2 is wrong.")
return self.cleaned_data
Update
如果您想要clean
在特定字段中引发错误的方法:
请注意,由 Form.clean() 覆盖引发的任何错误都不会被
与任何特定领域相关。他们进入一个特殊的
“场”(称为all),您可以通过以下方式访问
如果需要的话,non_field_errors() 方法。如果你想附加错误
对于表单中的特定字段,您需要调用add_error()。
所以从 Django 文档中你可以使用add_error()
做你想达到的目标。
代码可以是这样的
def clean(self):
"""
In here you can validate the two fields
raise ValidationError if you see anything goes wrong.
for example if you want to make sure that field1 != field2
"""
field1 = self.cleaned_data['field1']
field2 = self.cleaned_data['field2']
if field1 == field2:
# This will raise the error in field1 errors. not across all the form
self.add_error("field1", "Your Error Message")
return self.cleaned_data
请注意,上述方法是 Django 1.7 及更高版本中的新方法。
https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.add_error https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.add_error