ModelAdmin provides a hook to get_readonly_fields () - the following is untested, my idea is to define all the fields as ModelAdmin does, without using recursion with the readonly fields themselves:
from django.contrib.admin.util import flatten_fieldsets class ReadOnlyAdmin(ModelAdmin): def get_readonly_fields(self, request, obj=None): if self.declared_fieldsets: fields = flatten_fieldsets(self.declared_fieldsets) else: form = self.get_formset(request, obj).form fields = form.base_fields.keys() return fields
then the subclass / mixin of this administrator, if he is to be a read-only administrator.
To add / remove, and so that their buttons disappear, you probably also want to add
def has_add_permission(self, request):
PS: In ModelAdmin, if has_change_permission (lookup or your override) returns False, you donโt get into the object's change view - and the link to it will not even be shown. It would be great if this happened, and by default get_readonly_fields () checked the permission to change, and in this case set all the fields to be read-only, as indicated above. That way, non-changers could at least view the data ... given that the current admin structure assumes view = edit, as jathanism points out, this will probably require the introduction of a โviewโ permission on top of the add / change / delete. ..
EDIT: regarding setting all read-only fields, also untested, but promising:
readonly_fields = MyModel._meta.get_all_field_names()
EDIT: here's another one
if self.declared_fieldsets: return flatten_fieldsets(self.declared_fieldsets) else: return list(set( [field.name for field in self.opts.local_fields] + [field.name for field in self.opts.local_many_to_many] ))
Danny W. Adair Nov 01 '11 at 10:32 2011-11-01 10:32
source share