0

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()

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.