Can I use multiple number of formset in a single form in django,if yes how?
Asked Answered
C

2

10

I have to make a form in which more than one formset is used. please tell me if this is possible. if yes then how?

Cardigan answered 4/7, 2012 at 7:54 Comment(0)
C
18

You can add as many formsets in the form. Just create/init them in view and pass to template to render in the form.

Something like:

{{ formset1.management_form }}
{% for form in formset1 %}
    {{ form }}
{% endfor %}

{{ formset2.management_form }}
{% for form in formset2 %}
    {{ form }}
{% endfor %}

You are using multiple formsets in one view, you need to use prefix for the forms as explained here Using more than one formset in a view In short:

article_formset = ArticleFormSet(prefix='articles')
book_formset = BookFormSet(prefix='books')
Cagey answered 5/7, 2012 at 4:22 Comment(3)
This does not work correctly. As the management form for both the formsets would be same, there is no way to distinguish between formset1.management_form and formset2.management_form in the template. Management form actually contains 3 hidden input field:<input type="hidden" name="form-TOTAL_FORMS" value="1" id="id_form-TOTAL_FORMS" /><input type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS" /><input type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS" /> and these are same for all formsets. I wonder why doesn't django distinguish between these.Densify
@tejinderss, you need to use prefix while creating formsets in view, refer docs.djangoproject.com/en/dev/topics/forms/formsets/…Cagey
This answer does not include the case in which same model or form is about to use; for example if we want to use a formset of formset in a single view.Wirewove
A
1

When adding a prefix='article' We need to consider that the id of the formset will change and there are other changes too like

<label for="id_form-0-title">Title:</label> 

<label for="id_article-0-title">Title:</label>
Arjun answered 4/9, 2019 at 3:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.