gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:18:58 26 4
gpt4 key购买 nike

我想知道是否可以向 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',
)

最佳答案

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

关于css - 如何将 css 类添加到 Django 管理表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46580638/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com