2012-04-07 94 views
3

我使用一個FileField字段和文本字段在我的形式Django的forms.FileField驗證

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。

+2

請問https://docs.djangoproject.com/en/dev/topics/http/file-uploads/有幫助嗎? – lazy1 2012-04-07 15:17:38

+0

+1 lazy1,只是檢查request.FILES ['file'] – okm 2012-04-07 15:22:03

+0

我不能在乾淨的方法()中做到這一點,那裏沒有請求變量。有沒有什麼方法可以用乾淨的方法來驗證? – 2012-04-07 15:36:43

回答

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 
+0

我的不好。我在「clean_text」而不是主要的「clean」方法中進行驗證。糾正這個技巧 – 2012-04-07 16:18:57