Django extends ModelAdmin fields and stores default values

there is a good way to add custom elements to a subclass of ModelAdmin class, i.e. save all default values ​​and only some additional functions.

(I know that I can add all the defaults, but was hoping for a better way)

+6
django-admin
source share
3 answers

You can override the get_fieldsets ModelAdmin method.

The default implementation is as follows:

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, as follows:

 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 
+10
source share

Unconfirmed, but may work:

 class MyAdmin(BaseAdmin): fieldsets = BaseAdmin.fieldsets + (...) 

This could (if it works) add other fields after the inherited ones.

0
source share

Here is an example of extending a custom ModelAdmin class and adding an extra set of fields.

Please note that the first time I tried this, I left the "if not ..." check. Each time I refresh the page, additional sections are 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) eg [ '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 
0
source share

All Articles