如何将CSS类添加到Django管理表单

时间:2017-10-05 07:58:24

标签: css django django-admin

我想知道是否可以在Django管理表单中添加css类?

例如:

@admin.register(SomeFunction)
class SomeFunctionAdmin(SortableAdmin):
    fieldsets = (
        (None, {
            'fields': ('item1', 'item2', 'item3'),
        }),
    )

    def get_form(self, request, obj=None, **kwargs):
        form = super(SomeFunctionAdmin, self).get_form(request, obj, **kwargs)
        return form

    class Media:
        js = (
            'custom.js',
        )

现在我想向SomeFunctionAdmin添加一个css类,假设我要添加.custom-form-admin类。在我的custom.js文件中,我有一些函数可以搜索这个自定义css类。

如何以编程方式将自定义css类添加到SomeFunctionAdmin

我想代码看起来像这样:

@admin.register(SomeFunction)
class SomeFunctionAdmin(SortableAdmin):
    fieldsets = (
        (None, {
            'fields': ('item1', 'item2', 'item3'),
        }),
    )

    def get_form(self, request, obj=None, **kwargs):
        form = super(SomeFunctionAdmin, self).get_form(request, obj, **kwargs)
        form.set_css += 'custom-form-admin'
        return form

    class Media:
        js = (
            'custom.js',
        )

1 个答案:

答案 0 :(得分:1)

您可以覆盖render_change_form()并修改内容:

from django.http import HttpResponse


@admin.register(SomeFunction)
class SomeFunctionAdmin(SortableAdmin):
    fieldsets = (
        (None, {
            'fields': ('item1', 'item2', 'item3'),
        }),
    )

    def render_change_form(self, *args, **kwargs):
        content = super(SomeFunctionAdmin, self).render_change_form(*args, **kwargs).render().content
        return HttpResponse(content.replace('<form', '<form class="custom-form-admin"'))

    class Media:
        js = (
            'custom.js',
        )