Search code examples
djangoformset

Django formset - surplus line is rendered in the table


I successfully render a table using Django formsets, but a suplus empty line is rendered in the end! What am I doing wrong ?

<table id="formset" class="form table table-condensed zeon zeon-row-hover">
                    {{ formset.management_form }}
                        
                    {% for form in formset.forms %}
                      {% if forloop.first %}
                      <thead><tr>
                        {% for field in form.visible_fields %}
                        <th>{{ field.label|capfirst }}
                        {% endfor %}
                      </tr></thead>
                      {% endif %}
                      <tr class="{% cycle row1,row2 %}">
                      {% for field in form.visible_fields %}
                        <td class = 'zeon_input_table_cell'>
                        {# Include the hidden fields in the form #}
                        {% if forloop.first %}
                              {% for hidden in form.hidden_fields %}
                              {{ hidden }}
                              {% endfor %}
                        {% endif %}
                          {{ field.errors.as_ul }}
                            {{field}}
                        </td>
                      {% endfor %}
                      </tr>
                    {% endfor %}    
                    </table>

View:

MyModelFormSet =  modelformset_factory(MyModel, exclude=('agreement_vendors',))
formset = MyModelFormSet(queryset = MyModel.objects.filter(...))
return render_to_response('vendors/edit_agreement.html',
                             {'formset':formset},
                              context_instance=RequestContext(request))
    

enter image description here

UPDATE: According to the answer below, the issue is solved putting extra = 0


Solution

  • According to the Django docs:

    As you can see it only displayed one empty form. The number of empty forms that is displayed is controlled by the extra parameter. By default, formset_factory() defines one extra form; the following example will display two blank forms:

    With that in mind, Django docs suggests doing something like this to set the number of extra forms:

    ArticleFormSet = formset_factory(ArticleForm, extra=2)