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
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With