django扩展ModelAdmin字段集并保留默认值

时间:2010-08-21 12:04:56

标签: django-admin

有一种很好的方法可以自定义项添加到子类的ModelAdmin字段集中,即保留所有默认值和一些额外内容。

(我知道我可以自己添加所有默认值,但希望有更好的方式)

4 个答案:

答案 0 :(得分:10)

您可以覆盖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

答案 1 :(得分:1)

未经测试,但可能有效:

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

这将(如果有效)在继承的字段集之后添加其他字段集。

答案 2 :(得分:0)

以下是扩展自定义ModelAdmin类并添加额外字段集的示例。

注意我第一次尝试这个时,我遗漏了“if not ...”检查。每次刷新页面时,页面上都会重复多个部分。

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

答案 3 :(得分:0)

#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 中更新它。