有没有一种好的方法可以向子类化的ModelAdmin字段集添加自定义项,即使它保留所有默认值并只添加一些额外内容。
(我知道我可以自己添加所有默认值,但希望有更好的方法)
(我知道我可以自己添加所有默认值,但希望有更好的方法)
你可以重写 ModelAdmin 的 get_fieldsets 方法。
默认实现如下:
def get_fieldsets(self, request, obj=None):
"Hook for specifying fieldsets for the add form."
if self.declared_fieldsets:
return self.declared_fieldsets
form = self.get_form(request, obj)
fields = form.base_fields.keys() + list(self.get_readonly_fields(request, obj))
return [(None, {'fields': fields})]
所以你可以像这样覆盖它:
class MyCustomAdmin(ModelAdmin):
def get_fieldsets(self, request, obj=None):
fs = super(MyCustomAdmin, self).get_fieldsets(request, obj)
# fs now contains [(None, {'fields': fields})], do with it whatever you want
all_fields = fs[0][1]['fields']
return fs
未经测试,但可能有效:
class MyAdmin(BaseAdmin):
fieldsets = BaseAdmin.fieldsets + (...)
#models.py
class CustomUser(AbstractUser, TimeStamped):
username = models.CharField(max_length=255, unique=True, blank=False,
null=False)
is_premium = models.BooleanField(default=False)
#admin.py
class CustomUserAdmin(UserAdmin):
model = CustomUser
add_form = CustomUserCreationForm
fieldsets = (
(None, {'fields': ('username', 'password')}),
(_('Personal info'), {'fields': ('first_name', 'last_name', 'email', 'is_premium')}),
(_('Permissions'), {
'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'),
}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
admin.site.register(CustomUser, CustomUserAdmin)
你只需要从UserAdmin中获取默认的字段集,并在CustomUserAdmin中进行更新。
class GISDataFileAdmin(admin.ModelAdmin):
# abbreviated version of detailed fieldsets (one fieldset named 'Datafile Info')
fieldsets = [('DataFile Info', {\
'fields': ('datafile_id', 'datafile_label', 'datafile_version')\
}),]
class ShapefileSetAdmin(GISDataFileAdmin):
# extend fieldsets in GISDataFileAdmin
def get_fieldsets(self, request, obj=None):
# get fieldset(s) from GISDataFileAdmin
#
fs = super(ShapefileSetAdmin, self).get_fieldsets(request, obj)
# pull out the fieldset name(s) e.g. [ 'DataFile Info']
#
section_names = [ x[0] for x in fs if x is not None and len(x) > 0 and not x[0] == '']
# check if new fieldset info has been added
# if not, add the new fieldset
#
if not 'Shapefile Info' in sections_names:
# Add new info as the top fieldset
fs = [ ('Shapefile Info', {
'fields': ('name', ('zipfile_checked', 'has_shapefile'))
})] + fs
return fs