2013-04-17 52 views
1

我想在每個Formset的CharField中使用字符串值,但由於某些原因,每個表單的Washing_data總是顯示爲空,而formset的清理數據不是。這是從我views.py代碼:Form's的清空數據是空的,但是formset的cleared_data不是?

TagsFormSet = formset_factory(TagsForm, formset=TagFormSet, extra=applicantQuery.count()) 
    if request.method == 'POST': 
     tags_formset = TagsFormSet(request.POST, request.FILES, prefix='tags', applicants=applicantQuery) 
     if tags_formset.is_valid(): 
      for tagForm in tags_formset.forms: 
       tagForm.saveTags() 

在我的形式如下:

class TagFormSet(BaseFormSet): 

def __init__(self, *args, **kwargs): 
    applicants = kwargs.pop('applicants') 
    super(TagFormSet, self).__init__(*args, **kwargs) 
    #after call to super, self.forms is populated with the forms 

    #associating first form with first applicant, second form with second applicant and so on 
    for index, form in enumerate(self.forms): 
     form.applicant = applicants[index] 

class TagsForm(forms.Form): 
    tags = forms.CharField() 
    def __init__(self, *args, **kwargs): 
     super(TagsForm, self).__init__(*args, **kwargs) 
     self.fields['tags'].required = False; 

    def saveTags(self): 
     Tag.objects.update(self.applicant, self.cleaned_data['tags']) 

正如我前面所說的,tags_formset.cleaned數據包含正確的信息,進入上該頁面,但表單的清理數據是空的。此代碼給了我一個KeyValue錯誤,說'標記'不在清理的數據中,因爲它沒有任何內容(在saveTags函數中拋出錯誤)。

回答

0

好吧,我只是想通了究竟發生了什麼(哇我愚蠢)。發生錯誤是因爲我做了tags.required False,但是如果該特定表單有任何輸入值,則可以調用saveTags。簡單的解決方法是檢查清潔數據字典是否爲空:

if tags_formset.is_valid(): 
    for tagForm in tags_formset.forms: 
     #check if cleaned_data is non-empty 
     if tagForm.cleaned_data: 
      tagForm.saveTags() 
相關問題