Django Admin: has_delete_permission Ignored for “Delete” Action

前端 未结 2 430
天涯浪人
天涯浪人 2021-02-02 17:24

Let\'s say that I have a model where the row that has an ID of 1 is special and should not be able to be deleted, but all the other rows are fine to delete. Here is my attempt a

2条回答
  •  感动是毒
    2021-02-02 17:55

    You can replace the admin's implementation of the delete_selected action with your own. Something like:

    from django.contrib.admin import actions
    
    class WidgetAdmin(admin.ModelAdmin):
        actions = [delete_selected]
    
        def delete_selected(self, request, queryset):
            # Handle this however you like. You could raise PermissionDenied,
            # or just remove it, and / or use the messages framework...
            queryset = queryset.exclude(pk=1)
    
            actions.delete_selected(self, request, queryset)
        delete_selected.short_description = "Delete stuff"
    

    See the documentation for more details.

提交回复
热议问题