Reputation: 37
In my django admin site I want to hide some fields to users within a group (Controllers group)
What would be the best approach? Can we do something like this?
This is my code, but it doesn't work:
admin.py:
class PriceFile(admin.ModelAdmin):
if User.groups.filter(name='Controllers').exists():
fieldsets = [(None, {'fields':['print_url', ('model', 'client'), 'description']})]
else:
fieldsets = [(None, {'fields':['print_url', ('model', 'client'), 'description', 'total_sum', 'margin_percent', 'final_price']})]
Upvotes: 3
Views: 1747
Reputation: 509
Did you already solve this?
Django Admins has a method called get_fieldsets
which you can use to decide which fieldset you can use to add. Your could would look like the following:
@admin.register(ModelName)
class ModelAdmin(admin.ModelAdmin):
def get_fieldsets(self, request, obj=None):
if request.user.is_superuser:
return self.superuser_fieldsets
else:
return self.staff_fieldsets
staff_fieldsets = (
(None, {'fields': ('regular_field_a', 'regular_field_b')})
)
superuser_fieldsets = (
(None, {'fields': ('regular_field_a', 'regular_field_b')}),
(None, {'fields': ('super_user_field_a', 'super_user_field_b')})
)
The function get_fieldsets
has access to the request and object, and what I do here is depending on the status of the user (is_superuser
in this case) we serve out a different fieldset. You can add in your own requirements, e.g. if a user is part of a authentication group, or if it depends on the object your are seeing.
Upvotes: 9