Exclude fields in Django admin for users other than superuser

后端 未结 6 1239
孤独总比滥情好
孤独总比滥情好 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:17

    Django now has a get_exclude method on ModelAdmin for excluding fields programmatically.

    It takes the current request and the object (if any) as argument. You can put a check there on the request argument to see if they're a superuser and check

    class MyModelAdmin(admin.ModelAdmin):
        def get_exclude(self, request, obj=None):
            excluded = super().get_exclude(request, obj) or [] # get overall excluded fields
    
            if not request.user.is_superuser: # if user is not a superuser
                return excluded + ['extra_field_to_exclude']
    
            return excluded # otherwise return the default excluded fields if any
    

提交回复
热议问题