如何在Wagtail管理面板的BaseSiteSetting中分配面板到标签页?
如何在BaseSiteSetting中为标签页分配面板
在Wagtail的Page类中添加标签页面板十分直观,示例代码如下:
author_panels = [ MultiFieldPanel( [ FieldPanel("Name"), ], heading=_("Author(s)"), ), ] @cached_classmethod def get_edit_handler(self): panels = self.get_panels().copy() panels += [ ObjectList(self.author_panels, heading=_("Author(s)")), ] edit_handler = TabbedInterface(panels) return edit_handler.bind_to_model(self)
但BaseSiteSetting的实现逻辑与Page类不同,直接套用上述方法无法生效。不过可以通过SettingsTab配合TabbedInterface实现简洁的标签页划分,无需依赖复杂的ModelForm辅助类,具体步骤如下:
- 定义标签页标识:创建
SettingsTab实例,指定标签ID、显示名称和排序优先级:
from django.utils.translation import gettext_lazy as _ from wagtail.contrib.settings.registry import SettingsTab profile_tab = SettingsTab("profile", _("Profile"), order=100) notifications_tab = SettingsTab("notifications", _("Notifications"), order=200)
- 配置SiteSetting子类:在自定义的
BaseSiteSetting子类中,分标签定义字段面板,通过get_edit_handler绑定标签与面板的关联,并在register_setting装饰器中声明标签:
from django.db import models from wagtail.contrib.settings.models import BaseSiteSetting, register_setting from wagtail.admin.edit_handlers import TabbedInterface, ObjectList, FieldPanel from wagtail.utils.decorators import cached_classmethod @register_setting(tabs=[profile_tab, notifications_tab]) class CustomSiteSettings(BaseSiteSetting): # 示例配置字段 site_contact_name = models.CharField(_("Contact Name"), max_length=200) enable_alert_notifications = models.BooleanField(_("Enable Alert Notifications"), default=True) # 分标签的面板配置 profile_panels = [ FieldPanel("site_contact_name"), ] notifications_panels = [ FieldPanel("enable_alert_notifications"), ] @cached_classmethod def get_edit_handler(cls): return TabbedInterface([ ObjectList(cls.profile_panels, heading=_("Profile"), tab_id="profile"), ObjectList(cls.notifications_panels, heading=_("Notifications"), tab_id="notifications"), ]).bind_to_model(cls)
完成上述配置后,即可在Wagtail后台的设置页面中看到与Account设置页一致的标签页划分效果。
内容的提问来源于stack exchange,提问作者Filip Woźniak
相关产品推荐
相关产品推荐

