嗨我有一个django表单,其中有一个单选按钮和几个字符字段。作为此表单验证的一部分,我想清理每个输入,然后进行一些额外的清理(即进一步清理下游数据)。
但是,当我进行额外的清洁工作时,在clean()中,在每个clean_()方法之后调用它。
有没有办法可以最后调用clean()?
form.py
class UploadForm(forms.ModelForm):
year = forms.IntegerField(label='Year:', required=True)
number = forms.IntegerField(label='Number:', required=True)
stored = forms.ChoiceField(
required=True,
label='Storage:',
widget=forms.RadioSelect,
choices=(('Routine', 'Routine',), ('Archive', 'Archive',))
)
def clean_year(self):
self.year = self.cleaned_data['year']
year_check = re.compile("\d{4}$")
if year_check.match(str(self.year)):
return(self.year)
else:
msg = "Year '%s' is incorrect." %(str(self.year))
logger.error(msg)
raise(forms.ValidationError(msg))
def clean_number(self):
self.number = self.cleaned_data['number']
number_check = re.compile("\d{1,2}$")
if number_check.match(str(self.number)):
return(self.number)
else:
msg = "Year '%s' is incorrect." %(str(self.number))
logger.error(msg)
raise(forms.ValidationError(msg))
def clean_stored(self):
try:
self.stored = self.cleaned_data['stored']
except:
self.stored = False
def clean(self):
self.more_cleaning_methods()
def more_cleaning_methods():
print(self.stored)
如果未选中存储的单选按钮,则会导致错误 - 而不是引发表单错误。这是因为首先调用clean() - 因此我的类对象没有" attribute 'stored'
"
有没有办法可以在单独清理字段输入后调用clean(),还是在我的字段输入后调用clean方法(在form.is_valid()== True之前)?
由于