I'm trying to use get_fieldsets
to organize admin model pages. Using fieldsets
is pretty satisfying, but I'm stuck with how to exclude some fields. Currently, I used if condition to check user type, and then return different fieldsets
based on user type. I'm having the same codes to be repeated because of that. Is there a way to exclude a few fields in get_fieldsets
?
admin.py
class StoreAdmin(admin.ModelAdmin):
...
def get_fieldsets(self, request, obj=None):
fieldsets = copy.deepcopy(super(StoreAdmin, self).get_fieldsets(request, obj))
if request.user.is_superuser:
return (
[
('Basic Information', {
'fields': (
('status', 'review_score', 'typ'),
('businessName', 'relatedName'),
('mKey'),
)
}),
('Additional Options', {
'fields': (
('affiliate_switch', 'is_affiliated', 'affiliate',),
)
}),
]
)
else:
return (
[
('Basic Information', {
'fields': (
('status', 'review_score', 'typ'),
('businessName', 'relatedName'),
('mKey'),
)
}),
]
)
If you only want to exclude fields you can use get_fields
instead as following:
def get_fields(self, request, obj=None):
fields = super(ClientAdmin, self).get_fields(request, obj)
if obj:
fields_to_remove = []
if request.user.is_superuser:
fields_to_remove = ['field1', 'field2', 'etc', ]
for field in fields_to_remove:
fields.remove(field)
return fields
Edit:
Same logic could be used for get_fieldsets
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With