我试图使所有字段为只读,而不明确列出它们。
就像是:
class CustomAdmin(admin.ModelAdmin): def get_readonly_fields(self, request, obj=None): if request.user.is_superuser: return self.readonly_fields return self.fields
目前CustomAdmin.fields尚未设置问题。
CustomAdmin.fields
小心,self.model._meta.fields不一定与CustomAdmin具有相同的字段!
self.model._meta.fields
“管理员的所有字段”看起来像这样:
from django.contrib import admin from django.contrib.admin.utils import flatten_fieldsets class CustomAdmin(admin.ModelAdmin): def get_readonly_fields(self, request, obj=None): if request.user.is_superuser: return self.readonly_fields 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] ))