check for deletion in save_related (admin.py)

Hey everyone, I have probably a very simple question, that i haven’t been able to figure out for a while.
Our django application had a hard crash whenever someone would delete anything in the administration panel. After narrowing it down to the following piece of code i found out what the problem was:

def save_related(self, request, form, formsets, change):
    for single_form in formsets:
        if single_form.model == Malfunction and single_form.has_changed():
            new_instance = single_form.save(commit=False)[0]

This is part of a class that extends ModelAdmin, and i omitted what comes after it for brevity. What this part is supposed to do, is when a related object has been changed, and the related object is of type Malfunction, it gets the changed instance of it.
My question is now however, if such an object has been deleted instead of changed, how can i check for that? Because if it has been deleted, that form.save() call will fail.

See the section of the formset docs on can_delete.

It looks like you’d want to check to see if single_form in formsets.deleted_forms, but that’s just a guess based on what I’m reading. (I’ve never had to do this manually.)

1 Like

Interesting, thank you a lot for your answer :slight_smile: I am rather more interested in checking for “is_deleted” instead of “can_delete”, cause if so, calling single_form.save() would fail.
I just discovered though, that all those forms that let you delete something, have a field associated with them called “DELETE”, which i can get in the save_related method to see if it’s set to true or not. If it’s set to true, that means the object was deleted, if not, that means i can continue doing what i was doing :smiley:
Thanks a lot for the help though, it is really appreciated :slight_smile:

The information about “is_deleted” is documented in the section for “can_delete”.

1 Like

Looks like it suggests using that same ‘DELETE’ field, then that’s what i’ll use :slight_smile: