UserDependentModelAdmin
python | by: dArignac
last edit: Aug, 2nd 2010 | jump to bottom
csrf_protect_m = method_decorator(csrf_protect) ## User dependent admin model. # This class allows to specify tuples of the listed fields and displayed fieldsets # for the editors and superusers. class UserDependentModelAdmin(admin.ModelAdmin): ## Class constructor, adding actions an/or links for the user fields. # @param model the model the admin site is created for # @param admin_site the admin site def __init__(self, model, admin_site): # this is performed regularly on the list_display tuple # do the same for the additional list_display fields self._add_actions_and_links_for_list_display('editor') self._add_actions_and_links_for_list_display('superuser') super(UserDependentModelAdmin, self).__init__(model, admin_site) ## Adds actions and/or links for the list_display tuple of the given user # definid list_type. # @param list_type the list_display type, currently 'editor' for editors or 'superuser' for superuser def _add_actions_and_links_for_list_display(self, list_type): if 'action_checkbox' not in getattr(self, 'list_display_' + list_type) and self.actions is not None: setattr( self, 'list_display_' + list_type, ['action_checkbox'] + list(getattr(self, 'list_display_' + list_type)) ) if not self.list_display_links: for name in getattr(self, 'list_display_' + list_type): if name != 'action_checkbox': self.list_display_links = [name] break ## View for listing the models. # Adjusts the list_display tuple according to the current user. # @param request the sent request # @param extra_content an additional context @csrf_protect_m def changelist_view(self, request, extra_context=None): if request.user.is_superuser: self.list_display = self.list_display_superuser else: self.list_display = self.list_display_editor return super(UserDependentModelAdmin, self).changelist_view(request, extra_context=extra_context) ## Returns the fieldsets depending on the user. # @param request the sent request # @param obj the model object if already persisted def get_fieldsets(self, request, obj=None): user = request.user if user is None or user.is_anonymous(): # never get here normally return () else: if user.is_superuser: return self.fieldsets_superuser else: return self.fieldsets_editor
67 views




