I have a Model that's managed by Django Admin. How to I customize the display of its edit form based on the currently logged in user? For example if someone other than the superuser is modifying the model, I want to hide certain fields.
It'd be great if I co开发者_Go百科uld set fields
based on request.user
A hackish way to do this is overwriting the list_display
variable EVERY time the changelist view is called:
class MyModelAdmin(admin.ModelAdmin)
def changelist_view(self, request, extra_context=None):
user = request.user
if user.is_superuser:
self.list_display = ['field1', 'field2']
else:
self.list_display = ['field1']
return super(MyModelAdmin, self).changelist_view(request, extra_context=None)
But set the variable every time to the desired value, since the same admin instance might be called for requests made by other users as well!
An interesting approach to change edit form is to only alter readonly fields list.
For this purpose only override function get_readonly_fields:
class MyModelAdmin(admin.ModelAdmin):
def get_readonly_fields(self, request, obj=None):
user = request.user
if user.is_superuser:
readonly = []
else:
readonly = ['field1']
return readonly
Regarding list_display modern approach to modify it is to redefine get_list_display:
Original definition just returns self.list_display
:
class ModelAdmin:
def get_list_display(self, request):
"""
Return a sequence containing the fields to be displayed on the
changelist.
"""
return self.list_display
So you can provide:
class MyModelAdmin(admin.ModelAdmin):
def get_list_display(self, request):
user = request.user
if user.is_superuser:
list_display = ['field1', 'field2']
else:
list_display = ['field1']
return list_display
I think a less hackish way is described in this answer: https://stackoverflow.com/a/16115125/710394
def get_list_display(self, request):
...whatever logic you need here...
精彩评论