2011-09-04 27 views
0

使用自定義表單內環路我創建在Django自定義窗體有4個不同的元素開始:在Django

class InputForm(forms.Form): 
    date = forms.DateField() 
    item1 = forms.CharField() 
    amount1 = forms.CharField() 
    category1 = forms.CharField() 

我想延長這種包括任何數量的項目,數量和類別。

item2 = forms.CharField() 
    amount2 = forms.CharField() 
    category3 = forms.CharField() 
    item3... 

我試着設置下面的循環,但它沒有工作。有誰知道如何使循環工作,或知道另一種方式,我可以避免輸入item2,item3,item4等?

items = [] 
amounts = [] 
categories = [] 

for i in range(1,3): 
    items.append('item' + str(i)) 
    amounts.append('amount' + str(i)) 
    categories.append('category' + str(i)) 

class InputForm(forms.Form): 
    for x in items: 
     x = forms.CharField() 
    for y in amounts: 
     y = forms.CharField() 
    for z in categories: 
     z = forms.CharField() 

回答

1

我認爲你要找的是formsets。例如:

class InputForm(forms.Form): 
    item = forms.CharField() 
    amount = forms.CharField() 
    category = forms.CharField() 

InputFormSet = formset_factory(InputForm) 

然後您使用InputFormSet來管理窗體的集合。如果您需要可變數量的項目,金額和彼此不相關的類別,則可以使用多個表單集。

+0

太棒了,非常感謝! – jyli7