Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent super user deletion in Django admin?

In django admin I have 4 users and a super user. I have Users with staff status that have limited access and cannot delete/view/edit users but the admin has authority over every other users and models. I do want the superuser to be able to access the users data and edit/modify/delete them but I do not want the superuser to be able to delete himself/herself. Currently the superuser can delete himself. Is there a way to disable the superuser delete by himself/herself in django?? Any help would be grateful.

Thanks

like image 249
bor Avatar asked Aug 28 '13 11:08

bor


2 Answers

DO NOT USE has_delete_permission() override as it is not being called on every object when you perform delete action from changelist.

Use signals to do it. Add this to any models.py

from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied

@receiver(pre_delete, sender=User)
def delete_user(sender, instance, **kwargs):
    if instance.is_superuser:
        raise PermissionDenied

The only drawback of this method is that nobody will be able to delete any super user. You will have to set users attribute "is_superuser" to False before you can delete it.

like image 90
Simanas Avatar answered Oct 16 '22 20:10

Simanas


You can try to override UserAdmin so that it won't allow deleting as documented here:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

class MyUserAdmin(UserAdmin):

    def has_delete_permission(self, request, obj=None):
       if obj is None:
           return True
       else:
           return not obj.is_superuser

admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
like image 42
augustomen Avatar answered Oct 16 '22 18:10

augustomen