In Django 1.4 documentation, it says that clean_<fieldname>
methods are run first, then form clean
method is executed.
在Django 1.4文档中,它说clean_
I have the following code sample. The form is used with FormPreview. When pmid
field is empty in the form, it should throw ValidationError
exception, but it doesn't happen.
我有以下代码示例。表单与FormPreview一起使用。当pmid字段为空时,它应该抛出ValidationError异常,但它不会发生。
class MyForm(forms.Form):
pmid = forms.CharField()
.. other fields ..
def clean(self):
cd = super(MyForm, self).clean()
cd['pmid'] # returns KeyError and it's not in cd
return cd
I don't override any clean_<field>
method.
我不重写任何clean_
1 个解决方案
#1
1
First, if all you want to do is ensure a field is not blank, then just add required=True
to it. For example:
首先,如果您要做的只是确保字段不是空的,那么只需添加required=True即可。例如:
class MyForm(forms.Form):
pmid = forms.CharField(required=True)
...
And you're done.
你就完成了。
However, even if you couldn't do it that way, you still wouldn't validate it in clean
, but in clean_<fieldname>
as the docs describe.
然而,即使您不能那样做,您仍然不会在clean中验证它,而是在如文档所描述的clean_
def clean_pmid(self):
pmid = self.cleaned_data.get('pmid')
if not pmid:
raise forms.ValidationError('pmid cannot be blank')
return pmid
#1
1
First, if all you want to do is ensure a field is not blank, then just add required=True
to it. For example:
首先,如果您要做的只是确保字段不是空的,那么只需添加required=True即可。例如:
class MyForm(forms.Form):
pmid = forms.CharField(required=True)
...
And you're done.
你就完成了。
However, even if you couldn't do it that way, you still wouldn't validate it in clean
, but in clean_<fieldname>
as the docs describe.
然而,即使您不能那样做,您仍然不会在clean中验证它,而是在如文档所描述的clean_
def clean_pmid(self):
pmid = self.cleaned_data.get('pmid')
if not pmid:
raise forms.ValidationError('pmid cannot be blank')
return pmid