django extend ModelAdmin fieldsets and keep defaults
is there a nice way to add custom items to a subclassed ModelAdmin fieldset, ie have it keep all the defaults and just some extras.
(i know i could add all the defaults back mysel开发者_C百科f, but was hoping for a nicer way)
You can override get_fieldsets method of ModelAdmin.
The default implementation looks like this:
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})]
So you can override it for example like this:
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
Untested, but may work:
class MyAdmin(BaseAdmin):
fieldsets = BaseAdmin.fieldsets + (...)
This would (if it works) add the other fieldsets after the inherited ones.
Here's an example of extending a custom ModelAdmin class and adding an extra fieldset.
Note the first time I tried this, I left out the "if not ..." check. Every time I refreshed the page, the extra sections were repeated on the page.
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
#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)
you just need to grab the default fieldsets from UserAdmin, and update it in your CustomUserAdmin.
精彩评论