2016-05-18 165 views
0

我有一個看起來像這樣的形式:Django的形式:對象沒有屬性

class PeopleForm(forms.Form): 
    adult = forms.IntegerField(min_value=1, initial=1) 
    children = forms.IntegerField(min_value=0, required = False) 

這種形式的數量依賴於其他形式的其它領域的價值。所以我在視圖中爲這個表單創建了formset。在最後的結果中,我需要到PeopleForm表格的字段adult,並創建應該看起來像這樣的字符串Adult=2, Adult=3

所以我的看法是這樣的:

PeopleFormSet = formset_factory(PeopleForm, extra = 1, max_num = 15) 
people_formset = PeopleFormSet(request.POST, prefix='people') 
    if people_formset.is_valid(): 
    adults = '' 
    for i in people_formset: 
     adults = i.adult 

但我有一個錯誤'PeopleForm' object has no attribute 'adult'。我不明白如何到people_formset的字段adult

回答

2

您可以從表格的cleaned_data訪問該值。

for form in people_formset: 
    adults = form.cleaned_data['adult'] 
+0

是不是'保存'方法只適用於'ModelForm'? – Ben

+1

@Ben,你說得對,我沒有發現'PeopleForm'是一個常規的形式。我已經刪除了這部分答案。 – Alasdair

相關問題