How to add a dynamic form to a django formset in templates without annoying copies of html template output?
I have a formset with unknown count of result forms, and
This self-answer is based on this post by Nick Lang, but we are going to simplify this way and we don't need to copy/paste whole form html anymore.
We have an inline formset which is created in a view like this:
items_formset = inlineformset_factory(Parent, Item, form=ItemForm, extra=1)
item_forms = items_formset()
Next, we need to create a template for out formset form, we can do it using empty_form property of formset instance, which generates a html form template where every "id" number of a form is replaced by __prefix__ string, for example:
{% crispy item_forms.empty_form item_forms.form.helper %} #}
-->
So, first we need to replace this __prefix__ by an id and add a form using this template.
Here is a form template code fragment, which we can use to create new elements:
Then we need to display main part of the form:
Finally we need to add some JS (jquery, tested with 1.9.1 and 2.1.0) to add a next formset form. Note we will not use underscore.js, since it's unneeded in this case: just str.replace to replace __prefix__ by next "id" number)
That's all, just click on "Add Item" button, and a new formset item will appear.
Be sure to replace this sample by your app_name/model_name.