contrib:admin dynamic list_display support
|Reported by:||Gabe Jackson||Owned by:||cyrus|
|Severity:||Normal||Keywords:||list_display override dynamic admin|
|Cc:||aviv.by@…, delinhabit@…||Triage Stage:||Ready for checkin|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
I was trying to add dynamic list_display support for the following use-case:
The admin area of a shop should have separate views for the owner and for the supplier. the supplier should not see all the fields that the owner can see (i.e cannot see WHO ordered the products which are being requested from the supplier). For this, I wanted to have a dynamic list_display based on request.user.
We need a decent way to do this. Currently I'm using the following hacky approach which seems to work:
class MyModelAdmin(ModelAdmin): list_display = ('dynamicfield', 'permanent 1', 'permanent 2') def preprocess_list_display(self, request): if 'dynamicfield' not in self.list_display: self.list_display.insert(1, 'dynamicfield') if not request.user.is_superuser: if 'myfield' in self.list_display: self.list_display.remove('dynamicfield') def changelist_view(self, request, extra_context=None): self.preprocess_list_display(request) return super(MyModelAdmin, self).changelist_view(request)
The re-insertion of the 'dynamicfield' value is neccessary because ModelAdmin instances seem to persist. so once you log in as a non-superuser and the field is gone, the field will always be gone (even if you log back in as a superuser).
I'm not sure if it is possible, but a better appraoch would be to instanciate the ModelAdmin classes with the request, like this, one could simply overwrite init and set list_display accordingly.
Change History (19)
comment:14 Changed 6 years ago by
|Patch needs improvement:||unset|
|Triage Stage:||Accepted → Ready for checkin|