Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render Django Formset Manually

When i render my formset using a loop, everything works.

When i try to render it manually by accessing each field separately ( for frontend purpose ) the form is rendering but the submit fail. Every fields are the same, so i guess there is a hidden field created when working with the formset that i dont know about.

Here a simplified sample of my working code

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
{{ formset.management_form }}
{% for p in formset %}
    {{p.as_p}}
    {% endfor %}
</form>

And a simplified example of what is not working

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
{{ formset.management_form }}
{% for p in formset %}
<span class="form-sub-label-container " style="vertical-align:top">
                    {{p.field1}}
                    <label class="form-sub-label" for="input_12_city" id="sublabel_12_city" style="min-height:13px"></label>
                  </span>
    < span class="another_span">
    {{p.field2}}
 </span>
## etc....
    {% endfor %}
</form>

Any idea ?

Thanks.

like image 547
dsimond Avatar asked Sep 08 '25 11:09

dsimond


1 Answers

If you want to render each formset form field manually, you have to add Django default hidden fields.

<form method="post">
    {% csrf_token %}
    {{ formset.management_form }}
    {% for p in formset %}
        {{ p.id }} # if formset is ModelFormSet
        {{ p.ORDER }} # if can_order=True
        {{ p.DELETE }} # if can_delete=True
        ... # your custom fields
    {% endfor %}
</form>
like image 193
EMiDU Avatar answered Sep 11 '25 00:09

EMiDU



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!