arulmr
arulmr

Reputation: 8846

Django admin - Disable user deletion

I have a django app in which I want to disable user deletion in admin. I have tried to disable actions and setting delete permission to false. But none of them worked.

from django.contrib.auth.models import User

class UserProfileAdmin(UserAdmin):
    actions = None

OR

    def has_delete_permission(self, request):
        return False

OR

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

admin.site.unregister(User)
admin.site.register(User, UserProfileAdmin)

But when I'm using the UserAdmin to add a inline to user information, it is working fine. So please suggest me a way to disable user deletion in django admin. Thanks in advance.

Upvotes: 10

Views: 8172

Answers (2)

okm
okm

Reputation: 23871

Overriding ModelAdmin.has_delete_permission should do the trick, your invoking signature is incorrect, it's missing an obj parameter

class UserProfileAdmin(UserAdmin):
    def has_delete_permission(self, request, obj=None): # note the obj=None
        return False

Furthermore, simply return False prevents all staffs including administrator from deleting items in the Django Admin, you may want to just tweak User/Group permissions to prevent those staff you don't want them to delete an User(), by removing their delete_userprofile and delete_user permissions.

Upvotes: 20

Dan Russell
Dan Russell

Reputation: 970

If your goal is to permanently remove the "Delete" button from the bottom of all admin change forms, you can do so by modifying the file .../django/contrib/admin/templatetags/admin_modify.py.

In particular, replace the lines:

    'show_delete_link': (not is_popup and context['has_delete_permission']
                          and (change or context['show_delete'])),

with:

    'show_delete_link': False,

and no admin change forms should show the Delete button in the bottom left.

Upvotes: -2

Related Questions