Remove bulk delete action from django admin

Django admin provides multiple options in list view like delete records in bulk. See the image below for your reference.

default-bulk-delete

 

delete_selected action is called when you select delete option from the list view. To disable delete_selected action globally, you can use disable_action() method. Add below code in your admins.py file.

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

This will disable the bulk delete option from all the list views. If we want delete_selected to enable on any specific model, then we can add this in modelAdmin.actions

actions = ['delete_selected', 'any_custom_action']

#source code

@admin.register(Users)
class UsersAdmin(admin.ModelAdmin):
   actions = ['delete_selected', 'any_custom_action']

   class Meta:
       model = Users

If you want to remove the delete button from the object detail page, you can set modelAdmin delete permission to False.

@admin.register(Users)
class UsersAdmin(admin.ModelAdmin):

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

   class Meta:
       model = Users

Conditionally enable or disable actions

If you want to conditionally enable or disable actions in list view drop down menu, you can do this by overriding ModelAdmin.get_actions().

get_actions() returns a dictionary of allowed actions. The dictionary keys are action names so you can use “del” to delete the dictionary key.

For example, If you want to enable the delete_selected action for user with name ADMINISTRATOR, you can do this in this way.

@admin.register(Users)
class UsersAdmin(admin.ModelAdmin):

   def get_actions(self, request):
       actions = super().get_actions(request)

       if request.user.username[0:].upper() != 'ADMINISTRATOR':
           if 'delete_selected' in actions:
               del actions['delete_selected']
       return actions

   class Meta:
       model = Users

You can add your custom action in django admin list view. For example, If you remove option to hard delete records and want to create custom action to soft delete records, you can follow steps shown in add custom actions in django admin list view

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top
Shares