Django forms.FileField验证

时间:2012-04-07 13:49:10

标签: python django forms validation

我在表单中使用了文件字段和文本字段

class SolutionForm(forms.Form):
    text = forms.CharField(widget=forms.Textarea, required=False)
    file  = forms.FileField(required=False)

我还定义了一个干净的方法:

def clean(self,*args, **kwargs):
    if (not self.data['file'] or self.data['text']):
         raise forms.ValidationError('Please enter your code in text box or upload an arrpopriate file.')
return self.data['text']

但是在提交表单时,我会收到以下错误:

"Key 'file' not found in <QueryDict: {u'text': [u''], u'csrfmiddlewaretoken': [u'c52ea10c16620d3ebf0a20f015a3711d'], u'version': [u'C 1.1.1']}>"

如何引用文件字段?

任何帮助都将不胜感激。

谢谢,

的Pankaj。

1 个答案:

答案 0 :(得分:3)

# inside SolutionForm class
def clean(self):
    if not (self.cleaned_data['file'] or self.cleaned_data['text']):
        raise forms.ValidationError('Please enter your code in text box or upload an appropriate file.')
    return self.cleaned_data