I'm using a modelformset to allow the user to add/edit/delete food item's on their restaurant's menu.
FoodItemFormset = modelformset_factory(FoodItem, fields = '__all__', can_delete = True)
I'm then iterating over all of the forms in my template and displaying them in a table:
<table>
<tr>
<th>Food Item</th>
<th></th> <!-- empty <th> lines up with hidden input field -->
<th>Delete</th>
</tr>
{% for form in food_formset %}
<tr>
{% for field in form %}
<td>{{ field }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<input type="submit" name="" value="Submit">
However, that can_delete
attribute does not only lead to a checkbox being rendered, it also renders the hidden field containing the object's id as an actual table element, leading to an empty gutter between the tables contents.
<td><input type="text" name="form-0-name" value="Mozzarella Sticks" maxlength="200" id="id_form-0-name"></td>
<td><input type="hidden" name="form-0-id" value="2" id="id_form-0-id"></td> <!-- this just looks like an empty gutter -->
<td><input type="checkbox" name="form-0-DELETE" id="id_form-0-DELETE"></td>
Is there a way to get around this? Thanks for any help.
CodePudding user response:
Loop over form.visible_fields
to only include visible fields
{% for field in form.visible_fields %}
<td>{{ field }}</td>
{% endfor %}
You will also need to render the hidden fields but this doesn't need to be in it's own table cell
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}