Amine Messaoudi
Amine Messaoudi

Reputation: 2279

django admin overriding delete_model not working with bulk delete

I want to disable deleting for a specific model instance

I overrided delete_model in the ModelAdmin as follows :

def delete_model(self, request, client):
    if client.schema_name == 'public':
        messages.set_level(request, messages.ERROR)
        messages.error(request, 'Suppression interdite pour la racine')
    else:
        super().delete_model(request, client)

It works when I click the delete button on change view

enter image description hereenter image description here

But not with bulk delete as the instance is deleted without preventing

enter image description here

How can I fix this ? I also realized that delete_model is not called with bulk delete which makes a bit weird.

Upvotes: 1

Views: 2950

Answers (1)

iklinac
iklinac

Reputation: 15738

As bulk delete admin action documentation already warns you

The “delete selected objects” action uses QuerySet.delete() for efficiency reasons, which has an important caveat: your model’s delete() method will not be called.

If you wish to override this behavior, you can override ModelAdmin.delete_queryset() or write a custom action which does deletion in your preferred manner – for example, by calling Model.delete() for each of the selected items.

For more background on bulk deletion, see the documentation on object deletion.

Upvotes: 7

Related Questions