I've got a piece of code similar to the following:
from django.forms import inlineformset_factory
class EmailForm(forms.ModelForm):
class Meta:
model = MyModel
EmailFormSet = inlineformset_factory(
MyRelatedModel,
MyModel,
form=EmailForm,
can_delete=True,
extra=0
)
And I've got a custom class-based view which works perfectly fine for creating/saving new MyModel instances and for editing existing instances.
When I mark a form / an instance for deletion, I can see my view receives the following POST method:
<QueryDict: {
'csrfmiddlewaretoken': ['XXX'],
'email-TOTAL_FORMS': ['1'],
'email-INITIAL_FORMS': ['1'],
'email-MIN_NUM_FORMS': ['0'],
'email-MAX_NUM_FORMS': ['1000'],
'email-0-id': ['94ef2d4c-b2fc-4082-a460-e4344ddb20d4'],
'email-0-value': ['12345'],
'email-0-DELETE': ['on'],
}>
I believe this is, again, the expected behavior, in particular the formset.data do contain {'email-0-DELETE': ['on']} and the form is valid.
However, the corresponding instance is not deleted. Indeed, when I display formset.deleted_forms, it turns out to be an empty list. Why?
I've tried to deep dive into Django's inner mechanisms and I've noticed the method deleted_forms relies on another called _should_delete_form which simply returns form.cleaned_data.get(DELETION_FIELD_NAME, False). But in my case, form.cleaned_data only contains {'value': '12345'}, no "DELETE" key... So how is _should_delete_form supposed to return something else than False? Am I supposed to explicitly add a DELETE field to EmailForm, isn't the formset supposed to manage that extra field?
"I'm not entirely sure what you're trying to achieve. But recently, I needed to check if I had a deleted form in a submitted formset using formset.deleted_forms. However, I was getting an empty list unless all forms were deleted.
In my case, I simply wanted to check if any forms were marked for deletion. So, I used the following line of code:
I'm not sure if this will work for your situation, but it might be worth a try. Good luck!"