Reputation: 2759
I'm creating a custom form in Django that begins with 4 different elements:
class InputForm(forms.Form):
date = forms.DateField()
item1 = forms.CharField()
amount1 = forms.CharField()
category1 = forms.CharField()
I'd like to extend this to include any number of items, amounts, and categories.
item2 = forms.CharField()
amount2 = forms.CharField()
category3 = forms.CharField()
item3...
I tried setting up the following loop, but it didn't work. Does anyone know how to make the loop work, or know another way I can avoid typing out item2, item3, item4, etc.?
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()
Upvotes: 0
Views: 61
Reputation: 5043
I think what you're looking for are formsets. For example:
class InputForm(forms.Form):
item = forms.CharField()
amount = forms.CharField()
category = forms.CharField()
InputFormSet = formset_factory(InputForm)
Then you use the InputFormSet
to manage the collection of forms. You can use multiple formsets if you need variable number of item, amount, and categories that aren't related to each other.
Upvotes: 1