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

发布于 2024-09-15 18:11:57 字数 117 浏览 5 评论 0原文

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

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

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 myself, but was hoping for a nicer way)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

哑剧 2024-09-22 18:11:57

您可以重写 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

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
顾铮苏瑾 2024-09-22 18:11:57

未经测试,但可能有效:

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

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

Untested, but may work:

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

This would (if it works) add the other fieldsets after the inherited ones.

只有影子陪我不离不弃 2024-09-22 18:11:57

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

请注意,我第一次尝试此操作时,我省略了“如果不是...”检查。每次刷新页面时,页面上都会重复多余的部分。

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

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
〃温暖了心ぐ 2024-09-22 18:11:57

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

#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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文