Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 263
arulmr Avatar asked Sep 18 '12 11:09

arulmr


1 Answers

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.

like image 115
okm Avatar answered Oct 08 '22 08:10

okm