Exclude fields in Django admin for users other than superuser

后端 未结 6 1136
孤独总比滥情好
孤独总比滥情好 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条回答
  •  梦毁少年i
    2021-02-04 05:20

    Accepted answer is close but as others point out, get_form is called multiple times on the same instance of the Admin model and the instance is reused, so you can end up with fields repeated or other users seeing the fields after self.fields is modified. Try this out in Django <=1.6:

    class MyAdmin(admin.ModelAdmin):
    
        normaluser_fields = ['field1','field2']
        superuser_fields = ['special_field1','special_field2']
    
        def get_form(self, request, obj=None, **kwargs):
            if request.user.is_superuser:
                self.fields = self.normaluser_fields + self.superuser_fields
            else:
                self.fields = self.normaluser_fields
    
            return super(MyAdmin, self).get_form(request, obj, **kwargs)
    

    Looks like, Django 1.7 introduces a get_fields() method you can override which is a much nicer approach:

    https://github.com/django/django/blob/d450af8a2687ca2e90a8790eb567f9a25ebce85b/django/contrib/admin/options.py#L276

提交回复
热议问题