Exclude fields in Django admin for users other than superuser

后端 未结 6 1126
孤独总比滥情好
孤独总比滥情好 2021-02-04 04:34

I have a simple MyUser class with PermissionsMixin. user.is_superuser equals True only for superusers. I\'d like to be able t

6条回答
  •  隐瞒了意图╮
    2021-02-04 05:19

    Starting Django 1.7 you can replace the base class of your model admin with something like:

    class SuperuserAwareModelAdmin(admin.ModelAdmin):
        superuser_fields = None
        superuser_fieldsets = None
    
        def get_fieldsets(self, request, obj = None):
            if request.user.is_superuser and self.superuser_fieldsets:
                return (self.fieldsets or tuple()) + self.superuser_fieldsets
            return super(SuperuserAwareModelAdmin, self).get_fieldsets(request, obj)
    
        def get_fields(self, request, obj = None):
            if request.user.is_superuser and self.superuser_fields:
                return (self.fields or tuple()) + self.superuser_fields
            return super(SuperuserAwareModelAdmin, self).get_fields(request, obj)
    

    Example:

    class MyModelAdmin(SuperuserAwareModelAdmin):
        superuser_fieldsets = (
            (_('Permissions'), {'fields': ('is_staff', )}),
        )
    

    The SuperuserAwareModelAdmin base class can also be created as a mixin.

提交回复
热议问题