Search code examples
djangodjango-formsinline-formset

Formset with variable number of empty forms


I hope this is clear - I would think it's a pretty standard thing to need to do.

I want to create a formset with a number of empty forms, but the number of blank forms needs to vary each time the formset is rendered. For example I can get 2 empty forms with:

MyFormSet = inlineformset_factory(ParentModel, MyModel, extra=2)
# and in the view...
f = MyFormSet() # has 2 empty forms.

But the problem is I don't know initially how many empty forms I want. Suppose I wanted to render a number of forms in an inline model formset in reponse to a GET parameter. MyFormSet() will now always give me 2, no more no less.

I'd like something like this:

MyFormSet = inlineformset_factory(ParentModel, MyModel)
# In the view...
f = MyFormSet(extra=some_number())
# ... render f

But obviously that doesn't work. Do I need to redefine MyFormSet using the formset_factory every time I want to render the formset with a different number of blank forms? Or am I missing something obvious?


Solution

  • You can just call inlineformset_factory with a dynamic extra parameter in your view, no problem. The django admin is even more dynamic than that ( subclassing on the fly and so on ).