I have managed to create a ModelForm that successfully uses a custom template with template_name = "core/forms/simple.html"
. I made that template by merging the files django/forms/div.html
and django/forms/field.html
.
However, I’m failing to do the same for formsets. I’m creating an inlineformset with inlineformset_factory
, passing formset=MyBaseFormSet
, which has template_name = "core/forms/inlineformset.html"
.
When I follow the same procedure for merging the form templates, my inlineformset.html
looks like this:
{{ formset.management_form }}
{% for form in formset %}
{{ form.errors }}
{% if form.errors and not form.fields %}
<div>
{% for field in form.hidden_fields %}{{ field }}{% endfor %}
</div>
{% endif %}
{% for field, errors in form.fields %}
<div {% with classes=field.css_classes %}
{% if classes %}class="{{ classes }}"{% endif %}
{% endwith %}>
{{ field.as_field_group }}
{% if forloop.last %}
{% for field in hidden_fields %}{{ field }}{% endfor %}
{% endif %}
</div>
{% endfor %}
{% if not form.fields and not form.errors %}
{% for field in form.hidden_fields %}{{ field }}{% endfor %}
{% endif %}
{% endfor %}
But I get an error from {% for field, errors in form.fields %}
:
ValueError: Need 2 values to unpack in for loop; got 10.
The number 10 is approximately my model fields. It seems that the formset’s form fields is different from a normal form’s fields? And therefore doesn’t contain errors
the same way?
So far my code above is almost identical to django’s builtin templates and I do not understand why it breaks. Is {{ form.as_div }}
using a different template from django/forms/div.html
? If so, I can’t find it.
Any help is appreciated.
EDIT: Please note that I have prepended any fields
iteration with form.fields
, which might be one of the reasons it breaks. e.g.:
{% for field in fields %} ==> {% for field in form.fields %}
I have also tried setting template_name_div
but nothing happens.