[Django]-Remove the default delete action in Django admin

84👍

This works:

def get_actions(self, request):
    actions = super().get_actions(request)
    if 'delete_selected' in actions:
        del actions['delete_selected']
    return actions

It’s also the recommended way to do this based off Django’s documentation below:

Conditionally enabling or disabling actions

31👍

In your admin class, define has_delete_permission to return False:

class YourModelAdmin(admin.ModelAdmin):
    ...

    def has_delete_permission(self, request, obj=None):
        return False

Then, it will not show delete button, and will not allow you to delete objects in admin interface.

15👍

You can disable “delete selected” action site-wide:

from django.contrib.admin import site
site.disable_action('delete_selected')

When you need to include this action, add 'delete_selected' to the action list:

actions = ['delete_selected']

Documentation

9👍

If you want to remove all the action:

class UserAdmin(admin.ModelAdmin):
    model = User
    actions = None

If you want some specific action:

class UserAdmin(admin.ModelAdmin):
    model = User
    actions = ['name_of_action_you_want_to_keep']

2👍

You can globally disable bulk delete action and enable for selected models only.

Documentation from django website

# Globally disable delete selected
admin.site.disable_action('delete_selected')

# This ModelAdmin will not have delete_selected available
class SomeModelAdmin(admin.ModelAdmin):
    actions = ['some_other_action']
    ...

# This one will
class AnotherModelAdmin(admin.ModelAdmin):
    actions = ['delete_selected', 'a_third_action']
    ...

1👍

Giving credit to @DawnTCherian, @tschale and @falsetru

I used:

class YourModelAdmin(admin.ModelAdmin):
...
  def get_actions(self, request):
      actions = super(YourModelAdmin, self).get_actions(request)
      try:
          del actions['delete_selected']
      except KeyError:
        pass
      return actions

  def has_delete_permission(self, request, obj=None):
      return False

It removes the delete action from the list view and the delete option from the detail view.

0👍

If you are using that model, as a foreign key in some other model.
Then by using PROTECT constraint for that foreign key you can disable deletion for that model in Django admin.

For Example,

class Exam(models.Model):
    student = models.ForeignKey(User, on_delete=models.PROTECT)
    marks = models.IntegerField(default=0)

By adding PROTECT constraint to User model through the foreign key present in Exam model, I have disabled the power (in Django admin or elsewhere) to delete students (User) who have written exams.

Leave a comment