elo80ka / django-dynamic-formset

A jQuery plugin that allows you dynamically add new forms to a rendered django formset.
677 stars 311 forks source link

Deleting instance not working when hideLastAddForm is true #197

Open corneliusabel opened 2 years ago

corneliusabel commented 2 years ago

When using inline formsets (extra=1, can_delete=True) and hideLastAddForm=true the deletion of an instance (after submitting) fails. However, with hideLastAddForm=false deletion works. I noticed that the only difference in the POST requests was the "TOTAL_FORMS" field which was n-1 when hideLastAddForm=true. That has prevented the deletion of the object in django. By commenting out line "totalForms.val(forms.length);" in line 95 (1.5-pre) i could fix that for me.

However, iam not an javascript expert so not sure if this is the right solution?

Best,

Cornelius

ridoo commented 6 months ago

My observation is rather that TOTAL_FORMS counter is decremented on delete. See

https://github.com/elo80ka/django-dynamic-formset/blob/38475fb944deb6a0fbcccf5b753adad0bba3261a/src/jquery.formset.js#L94-L95

and

https://github.com/elo80ka/django-dynamic-formset/blob/38475fb944deb6a0fbcccf5b753adad0bba3261a/src/jquery.formset.js#L98-L100

For what I traced in the Django code is, that the TOTAL_FORMS count has to include both visible and hidden form groups in the formset, as all form data is POSTed (deleted ones are marked with DELETE: "on" attribute). Decreasing the counter would not make the formset creating any (initial) forms for data having an index bigger than the decreased TOTAL_FORMS.