django 1.7: inlines not deleted when save_formset is overridden

1,351 views
Skip to first unread message

scott baker

unread,
Sep 18, 2014, 7:21:22 PM9/18/14
to django...@googlegroups.com
I've modified an Admin with code similar to the following:

    def save_formset(self, request, form, formset, change):
        instances = formset.save(commit=False)
        for instance in instances:
            instance.user = request.user
            instance.save()
        formset.save_m2m()


The problem I'm having is that if a "delete" checkbox is checked, the inline does not get deleted. I tracked this down to forms/models.py:save_existing_objects(). In Django 1.5 it deleted objects regardless of the setting of the commit argument. In django 1.7, it does not delete the objects if commit==False.

Am I missing something in the above that I need to do in order to cause my deleted inlines to be deleted? I can do it by looping through formset.deleted_forms myself (basically duplicating the code from save_existing_objects), but this feels like the wrong way to go about it.

Thanks,
Scott

Collin Anderson

unread,
Sep 19, 2014, 7:19:53 PM9/19/14
to django...@googlegroups.com
Wow. It took a lot of digging, but your situation is documented in https://docs.djangoproject.com/en/1.7/topics/forms/formsets/#django.forms.formsets.BaseFormSet.can_delete

another thing that might also work in your case:

def save_formset(self, request, form, formset, change):

   
for form in formset.forms:
        form
.instance.user = request.user
    formset
.save()

michel bruavics

unread,
Aug 6, 2020, 5:02:48 AM8/6/20
to Django users
Hello from the future!

This should work:

def save_formset(self, request, form, formset, change):
    print(formset)
instances = formset.save(commit=False)
for obj in formset.deleted_objects:
obj.delete()
for instance in instances:
instance.created_by = request.user
instance.created_at = timezone.now()
# Do something with `instance`
instance.save()
formset.save_m2m()
Reply all
Reply to author
Forward
0 new messages