Reputation: 3215
I am reading Django docs and don’t quite understand the comment below about formsets.
Why do I need to be aware to use the management form inside the management template in this example ?
Using a formset in views and templates
Using a formset inside a view is as easy as using a regular Form class. The only thing you will want to be aware of is making sure to use the management form inside the template. Let’s look at a sample view:
from django.forms import formset_factory
from django.shortcuts import render
from myapp.forms import ArticleForm
def manage_articles(request):
ArticleFormSet = formset_factory(ArticleForm)
if request.method == 'POST':
formset = ArticleFormSet(request.POST, request.FILES)
if formset.is_valid():
# do something with the formset.cleaned_data
pass
else:
formset = ArticleFormSet()
return render(request, 'manage_articles.html', {'formset': formset})
# manage_articles.html
<form method="post">
{{ formset.management_form }}
<table>
{% for form in formset %}
{{ form }}
{% endfor %}
</table>
</form>
Upvotes: 3
Views: 5764
Reputation: 1
If you were to render the whole {{ formset }}
in the template at once, you could then inspect your source code using your browser dev tool and see some hidden fields (<input type="hidden" />
) at the beginning of your form tag.
These fields are globally for control purpose and are configured through the arguments you provide to formset_factory, allowing Django to check if the form that is sent follows right the configuration you made (i.e. accept maximum 3 forms). Django absolutely needs those hidden fields to be sent along with the form data in order to know "what to do".
This is actually what Django calls Formset Management as you mentioned.
The problem occurs when you decide to be more specific regarding form template rendering: if you select what you want to render from the formset (i.e. {% for form in formset.forms %}
), you then lose the other parts that made your formset be a formset. You guessed it, I am refering to the formset management.
Therefore, we need to explicitly render it in our template since it is a part that is no longer rendered, with {{ formset.management_form }}
.
Upvotes: 0