I am using a script to control my Django formsets. The idea is to dynamically generate, remove and rename the forms. It works fine if the page was loaded for the first time, but if I try to submit the page and the forms get back from the POST, the old forms I can not delete. Although I can add and remove new ones.
function deleteForm(btn, prefix) {
var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
if (formCount > 1) {
// Delete the item/form
$(btn).parents('.item-wrapper').remove();
var forms = $('.item-wrapper'); // Get all the forms
// Update the total number of forms (1 less than before)
$('#id_' + prefix + '-TOTAL_FORMS').val(forms.length);
var i = 0;
// Go through the forms and set their indices, names and IDs
for (formCount = forms.length; i < formCount; i++) {
$(forms.get(i)).find('*').each(function () {
updateElementIndex(this, prefix, i);
});
}
} // End if
else {
alert("You must have at least one item in your invoice.");
}
return false;
}
Here is my HTML:
{{ formset.management_form }}
{% for form in formset %}
<div class="item-wrapper">
<div class="item-inner-wrapper">
<div class="item-child-name">
{{ form.name.label_tag }}
<div class="ui-widget">{{ form.name }}</div>
</div>
</div>
</div>
<!-- OTHER INPUTS --->
<div class="item-action-button">
<a id="delete" href="#" class="button alt small special">Remove</a>
<a id="hide-desc" class="button alt small">+ Description</a>
</div>
{% endfor %}