[Fixed]-Django formset not validating because ID is required

30👍

ModelFormsets require form.id. It is rendered as a hidden field. You will need to implement it with both formsets.

{% for form in formset %}
    {% for hidden in form.hidden_fields %}
        {{ hidden }}
    {% endfor %}
    <!-- form.visible fields go here -->
{% endfor %}

9👍

As an addendum to @unixo ‘s answer, simply putting:

{{ form.id }}

without any surrounding HTML tags, will be converted to the following when the template is rendered (values for name, value and id will be generated by your formset_factory):

<input type="hidden" name="form-1-id" value="2" id="id_form-1-id">

Just make sure it’s indented into the for form in formset loop.

Meaning you don’t need to add class="hidden" unless you have some particular handling of hidden fields you want.

3👍

The error message is very clear in this case: you’ve to render the “id” field otherwise the POST won’t contain the primary key value of each record.

I’d suggest using crispy forms and let it renders the entire formset or manually render the field in the template.
In the first case, you’d have something like this:

{% load crispy_forms_tags %}
<form action="post" ...>
    {% crispy formset %}
</form>

Otherwise:

<form action="post" ...> 
    <table>
        <tbody>
           {% for form in formset %}
           <tr>
              <td>{{ form.field1 }}</td>
              <td>{{ form.field2 }}</td>
              <td class="hidden">{{ form.id }}</td>
           </tr>
        </tbody>
    </table>             
</form>
👤unixo

Leave a comment