如何在表单中创建第一个或第二个属性?
在此表单中,我希望用户填写text_to_translate
或file
。
我试图为这两个属性创建clean_something
,但它似乎无效。它引起了 -
KeyError异常值:'file'
可能是因为调用clean_text_to_translate
方法时,file
尚未清除。
你知道该怎么办吗?
class NewOrderForm(forms.ModelForm):
text_to_translate = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'Specification'}), required=False)
file = forms.FileField(required=False)
delivery_date = forms.DateField(label='Deadline', widget=SelectDateWidget(years=[y for y in range(1930, 2050)]))
class Meta:
model = Job
fields = (
'short_description', 'language_from', 'text_to_translate', 'file', 'notes','style', 'delivery_date',
)
widgets = {
'text_to_translate': forms.Textarea(attrs={'class': 'form-control'}),
'language_from': forms.Select(attrs={'class': 'dropdown'})
# 'level':forms.Select(attrs={'class': 'form-control'}),
}
def clean_text_to_translate(self):
if self.cleaned_data['file'] is None:
return self.cleaned_data['file']
return ValidationError('You can fill either text to translate or attach a file')
def clean_file(self):
if self.cleaned_data['text_to_translate']=='':
return self.cleaned_data['text_to_translate']
return ValidationError('You can fill either text to translate or attach a file')
答案 0 :(得分:3)
您正在验证两个相互依赖的字段 - documentation中对此进行了描述。文档建议使用表单的clean()方法进行验证:
我们一次在多个字段上执行验证,因此表单的clean()方法是执行此操作的好地方。
此时您可以获得在各个字段中存活的所有值。验证 - 请记住,text_to_translate
和file
可能为空 - 请勿使用方括号表示法访问这些值,而是使用cleaned_data.get()
。您的clean()方法可能如下所示:
def clean(self):
cleaned_data = super(NewOrderForm, self).clean()
file = cleaned_data.get("file")
text_to_translate = cleaned_data.get("text_to_translate")
if file and text_to_translate: # both fields were filled
raise forms.ValidationError("You must provide either text or file, not both.")
elif not (file or text_to_translate) # neither one was filled
raise forms.ValidationError("You must provide either text or file")
当然,您需要在模板中使用{{ form.non_field_errors }}
显示该错误。