Django user permissions allows is_superuser

Tue Mar 29, 2011

Small issue we found, if you want to give someone the ability to add/edit/delete users but don’t want them to be able to elevate privileges by setting is_superuser you have to monkey patch the UserAdmin class like this:

from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext_lazy as _

class MyUserAdmin(UserAdmin):
   my_fieldsets = (
       (None, {'fields': ('username', 'password')}),
      (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
       (_('Permissions'), {'fields':('is_active',)}),

def change_view(self, request, object_id, extra_context=None):
     # for non-superuser
     if not request.user.is_superuser:
         self.fieldsets = self.my_fieldsets
         response = UserAdmin.change_view(self, request, object_id,
         return response
         return UserAdmin.change_view(self, request, object_id,
extra_context=None), MyUserAdmin)

Then they won’t see the is_superuser checkbox. You’ll have to get a bit more fancy if you want to allow permission changes, but this is a good start.