<a id="panels-reference"></a>

# 面板

<a id="editing-api"></a>

## 内置字段与选择器

Wagtail 的面板机制会自动识别 Django 模型字段，并为它们提供合适的输入小部件。使用方法是在 Django 模型中按常规定义字段，然后在定义面板时把字段名传入
[`FieldPanel`](#wagtail.admin.panels.FieldPanel)（或合适的面板类型）。

下面是一些可在面板定义中使用的内置面板类型。它们都是基础 [`Panel`](#wagtail.admin.panels.Panel) 类的子类，除非另有说明，它们在自身参数之外还接受 `Panel` 的所有参数。

<a id="field-panel"></a>

### FieldPanel

### *class* wagtail.admin.panels.FieldPanel(field_name, widget=None, disable_comments=None, permission=None, read_only=False, required_on_save=None, \*\*kwargs)

这是用于基本 Django 模型字段类型的面板。它会依据模型字段定义提供默认的图标和标题，但也可以通过向构造函数传入额外参数来定制。更多细节见 [面板定制](#customizing-panels)。

#### field_name

这是你的模型定义中所用的类属性名。

#### widget(optional)

该参数允许你指定一个 [Django 表单小部件](https://docs.djangoproject.com/en/stable/ref/forms/widgets/)，用以代替该字段类型的默认小部件。

#### disable_comments(optional)

当设为 `True` 时，可以阻止该面板显示字段级评论按钮。见 [创建与编辑评论](https://guide.wagtail.org/en/how-to-guides/manage-pages/#create-and-edit-comments)。

#### permission(optional)

允许把字段选择性地展示给具备相应权限的用户。接受权限代号，例如 `'myapp.change_blog_category'` —— 如果登录用户没有该权限，该字段就会从表单中省略。关于如何设置权限的细节，见 Django 关于 [自定义权限](https://docs.djangoproject.com/en/stable/topics/auth/customizing/#custom-permissions) 的文档；另外，如果你想把某个字段设为仅超级用户可用，可以用任意字符串（例如 `'superuser'`）作为代号，因为超级用户会自动通过所有权限检查。

#### read_only(optional)

允许你阻止编辑者设置或更新模型字段的值。

对于大多数字段类型，字段值会在表单中渲染出来供编辑者查看（连同字段的标签和帮助文本），但不会显示任何表单输入控件，表单也会忽略在 POST 数据中改动该值的尝试，例如在提交前往表单 HTML 中注入隐藏输入框的做法。

默认情况下，`StreamField` 或 `RichTextField` 的字段值会被遮蔽处理，以防止在表单中间渲染可能不安全的 HTML。你可以通过覆盖 `Panel.format_value_for_display()` 为自定义面板类型改变这一行为。

#### required_on_save(optional)

指定在以草稿方式保存时，是否应对该字段强制执行必填约束。

对于页面模型，以及使用 [DraftStateMixin](../topics/snippets/features.html.md#wagtailsnippets-saving-draft-changes-of-snippets) 的 Snippet，以草稿方式保存默认会跳过必填字段的校验 —— 这让编辑者可以在内容尚未完成时保存草稿。必填字段的校验会在页面或 Snippet 被发布、定时发布或提交到工作流时执行。要覆盖这一行为并在保存草稿时强制执行校验，请把 `required_on_save` 设为 `True`。这也可以通过直接在模型字段上设置 `required_on_save` 属性来实现：

```python
subtitle = models.CharField(max_length=255)
subtitle.required_on_save = True
```

注意，未定义为 `null=True` 的非文本字段（例如 `IntegerField` 和 `DateField`）在数据库层面不允许保存空值，因此这些字段在保存草稿时始终会被当作必填字段强制执行。

#### attrs(optional)

允许设置在渲染出的面板上的 HTML 属性字典。如果把某个属性赋值为 `True` 或 `False`，它会被渲染为 HTML5 布尔属性。

#### NOTE
面板定义中的纯字符串等价于不带参数的 FieldPanel。

请使用这种写法：

```python
    content_panels = Page.content_panels + ["title", "body"]
```

而不是

```python
    content_panels = Page.content_panels + [
        FieldPanel('title'),
        FieldPanel('body'),
    ]
```

<a id="multifieldpanel"></a>

### MultiFieldPanel

### *class* wagtail.admin.panels.MultiFieldPanel(children=(), \*args, permission=None, \*\*kwargs)

该面板把若干 [`FieldPanel`](#wagtail.admin.panels.FieldPanel) 或选择器（以 `list` 或 `tuple` 形式给出）收纳在一个 `heading` 字符串之下。要节省空间，你可以 [默认把该面板折叠起来](#collapsible)。

#### children

子面板的 `list` 或 `tuple`

#### permission(optional)

允许把面板选择性地展示给具备相应权限的用户。接受权限代号，例如 `'myapp.change_blog_category'` —— 如果登录用户没有该权限，该面板就会从表单中省略。与 [`FieldPanel.permission`](#wagtail.admin.panels.FieldPanel.permission) 类似。

#### attrs(optional)

允许设置在渲染出的面板上的 HTML 属性字典。如果把某个属性赋值为 `True` 或 `False`，它会被渲染为 HTML5 布尔属性。

<a id="inline-panels"></a>

### InlinePanel

### *class* wagtail.admin.panels.InlinePanel(relation_name, panels=None, label='', min_num=None, max_num=None, \*\*kwargs)

该面板允许通过到另一个模型的关联来创建一组「簇」状的相关对象，例如一组相关链接，或轮播图的幻灯片。关于 `InlinePanel` 完整用法，见 [内联模型](../topics/pages.html.md#inline-models)。要节省空间，你可以 [默认把该面板折叠起来](#collapsible)。

#### relation_name

赋予该簇的 ParentalKey 关系的 related_name 标签。

#### panels(optional)

组成子对象表单的面板列表。如果这里未指定，则使用子模型上的 panels 定义。

#### label

添加按钮的文本，以及子面板的标题。在没有 `heading` 时作为标题使用。

#### min_num(optional)

用户必须提交的表单最小数量。

#### max_num(optional)

用户必须提交的表单最大数量。

#### attrs(optional)

允许设置在渲染出的面板上的 HTML 属性字典。如果把某个属性赋值为 `True` 或 `False`，它会被渲染为 HTML5 布尔属性。

#### NOTE
面板定义中的纯字符串等价于不带参数的 InlinePanel。

请使用这种写法：

```python
    content_panels = Page.content_panels + ["gallery_images"]
```

而不是

```python
    content_panels = Page.content_panels + [
        InlinePanel('gallery_images'),
    ]
```

<a id="inline-panel-events"></a>

#### JavaScript DOM 事件

你可能想在 `InlinePanel` 条目就绪、被添加或被移除时执行一些 JavaScript。`w-formset:ready`、`w-formset:added` 和 `w-formset:removed` 事件可以实现这一点。

例如，给定一个在 `BlogPage` 上提供 Blog 与 Person 之间关系的子模型：

```python
class CustomInlinePanel(InlinePanel):
    class BoundPanel(InlinePanel.BoundPanel):
        class Media:
            js = ["js/inline-panel.js"]


class BlogPage(Page):
    # .. 字段

    content_panels = Page.content_panels + [
        CustomInlinePanel("blog_person_relationship"),
        # ... 其它面板
    ]
```

JavaScript 的用法如下。

```javascript
// static/js/inline-panel.js

document.addEventListener('w-formset:ready', function (event) {
    console.info('ready', event);
});

document.addEventListener('w-formset:added', function (event) {
    console.info('added', event);
});

document.addEventListener('w-formset:removed', function (event) {
    console.info('removed', event);
});
```

这些事件会被派发，可用于触发自定义 JavaScript 逻辑，例如设置自定义小部件。

<a id="multiple-chooser-panel"></a>

### MultipleChooserPanel

### *class* wagtail.admin.panels.MultipleChooserPanel(relation_name, chooser_field_name=None, panels=None, label='', min_num=None, max_num=None, \*\*kwargs)

该面板是 `InlinePanel` 的一个变体，可用于内联模型包含一个指向实现了 Wagtail 选择器接口的模型的 `ForeignKey` 关系时。
Wagtail 的图片、文档、Snippet 和页面都实现了该接口，其它模型也可以通过[注册自定义 ChooserViewSet](../extending/generic_views.html.md#chooserviewset)来实现。

「添加」按钮不会插入一个需逐个填写的新表单，而是立即打开该相关对象的选择器界面，并处于允许多选的模式。随后用户会回到主编辑表单，并已添加、预填好相应数量的子面板。

`MultipleChooserPanel` 额外接受一个必需参数 `chooser_field_name`，用于指定选择器所关联的 `ForeignKey` 关系的名称。

例如，给定一个在 `BlogPage` 上提供图片库的子模型：

```python
class BlogPageGalleryImage(Orderable):
    page = ParentalKey(BlogPage, on_delete=models.CASCADE, related_name='gallery_images')
    image = models.ForeignKey(
        'wagtailimages.Image', on_delete=models.CASCADE, related_name='+'
    )
    caption = models.CharField(blank=True, max_length=250)

    panels = [
        FieldPanel('image'),
        FieldPanel('caption'),
    ]
```

`BlogPage` 上的 `MultipleChooserPanel` 定义会是：

```python
        MultipleChooserPanel(
            'gallery_images', label="Gallery images", chooser_field_name="image"
        )
```

### FieldRowPanel

### *class* wagtail.admin.panels.FieldRowPanel(children=(), \*args, permission=None, \*\*kwargs)

该面板在编辑界面中创建分栏布局，每个子面板并排出现，而不是上下排列。

对复杂模型来说，使用 `FieldRowPanel` 特别有助于减少页面上字段过多带来的「雪盲」效应。它还能改善同类字段之间被感知到的关联性。例如，如果你创建了一个表示「事件」的模型，它有开始日期和结束日期，把开始和结束日期放在同一「行」上会更直观。

默认情况下，面板被划分为等宽的列，但可以通过为 FieldRowPanel 的每个子面板添加 `col*` 类名来覆盖。Wagtail 的编辑界面使用网格系统布局。可以把 `col1` 到 `col12` 的类应用到 FieldRowPanel 的每个子项上，以定义它们在总列数中占多少列。当网格项合计为 12 列时，`col3` 类会确保该字段占 3 列宽，即四分之一宽。`col4` 会让该字段占 4 列宽，即三分之一宽。

#### children

在该行中显示的子面板 `list` 或 `tuple`

#### permission(optional)

允许把面板选择性地展示给具备相应权限的用户。接受权限代号，例如 `'myapp.change_blog_category'` —— 如果登录用户没有该权限，该面板就会从表单中省略。与 [`FieldPanel.permission`](#wagtail.admin.panels.FieldPanel.permission) 类似。

#### attrs(optional)

允许设置在渲染出的面板上的 HTML 属性字典。如果把某个属性赋值为 `True` 或 `False`，它会被渲染为 HTML5 布尔属性。

### HelpPanel

### *class* wagtail.admin.panels.HelpPanel(content='', template='wagtailadmin/panels/help_panel.html', \*\*kwargs)

A panel to display helpful information to the user.

This panel does not support the `help_text` parameter.

#### content

在面板中显示的 HTML 字符串。

#### template

渲染完整面板 HTML 的模板路径。

#### attrs(optional)

允许设置在渲染出的面板上的 HTML 属性字典。如果把某个属性赋值为 `True` 或 `False`，它会被渲染为 HTML5 布尔属性。

### PageChooserPanel

### *class* wagtail.admin.panels.PageChooserPanel(field_name, page_type=None, can_choose_root=False, \*\*kwargs)

虽然 `FieldPanel` 也支持指向 [`Page`](models.html.md#wagtail.models.Page) 模型的 `ForeignKey`，但你可以显式使用 `PageChooserPanel` 来获得 `Page` 专属的定制能力。

```python
from wagtail.models import Page
from wagtail.admin.panels import PageChooserPanel


class BookPage(Page):
    related_page = models.ForeignKey(
        'wagtailcore.Page',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+',
    )

    content_panels = Page.content_panels + [
        PageChooserPanel('related_page', 'demo.PublisherPage'),
    ]
```

`PageChooserPanel` 接受一个必需参数，即字段名。此外可选地指定一个页面类型（以 `"appname.modelname"` 字符串形式给出），会过滤选择器，使其只显示该类型的页面。也可以传入页面类型的列表或元组，以允许选择匹配其中任一页面类型的页面：

```python
PageChooserPanel('related_page', ['demo.PublisherPage', 'demo.AuthorPage'])
```

传入 `can_choose_root=True` 会允许编辑者把页面树的根节点选作页面。通常这并不可取，因为根节点永远不是可用的页面，但在某些特殊场景下可能是恰当的；例如，一个带自动「相关文章」信息流的页面，可以用 `PageChooserPanel` 选择从哪个子区域取文章，而根节点对应「所有地方」。

### FormSubmissionsPanel

### *class* wagtail.contrib.forms.panels.FormSubmissionsPanel(\*\*kwargs)

该面板为实现了 `wagtail.contrib.forms.models.AbstractForm` 模型的页面，在编辑界面中添加一个只读区域。
它包含该表单的总提交数，以及一个指向提交列表的链接。

```python
from wagtail.contrib.forms.models import AbstractForm
from wagtail.contrib.forms.panels import FormSubmissionsPanel

class ContactFormPage(AbstractForm):
    content_panels = [
        FormSubmissionsPanel(),
    ]
```

<a id="title-field-panel"></a>

### TitleFieldPanel

### *class* wagtail.admin.panels.TitleFieldPanel(\*args, apply_if_live=False, classname='title', placeholder=True, targets=None, \*\*kwargs)

Prepares the default widget attributes that are used on Page title fields.
Can be used outside of pages to easily enable the slug field sync functionality.

* **参数:**
  * **apply_if_live** -- (optional) If `True`, the built in slug sync behaviour will apply irrespective of the published state.
    The default is `False`, where the slug sync will only apply when the instance is not live (or does not have a live property).
  * **classname** -- (optional) A CSS class name to add to the panel's HTML element. Default is `"title"`.
  * **placeholder** -- (optional) If a value is provided, it will be used as the field's placeholder, if `False` is provided no placeholder will be shown.
    If `True`, a placeholder value of `"Title*"` will be used or `"Page Title*"` if the model is a `Page` model.
    The default is `True`. If a widget is provided with a placeholder, the widget's value will be used instead.
  * **targets** -- (optional) This allows you to override the default target of the field named slug on the form.
    Accepts a list of field names, default is `["slug"]`.
    Note that the slugify/urlify behaviour relies on usage of the `wagtail.admin.widgets.slug` widget on the slug field.

这是用于页面 title 字段或其它模型主标题的面板。它提供默认的类名、占位符和小部件属性，以实现与表单中 slug 字段的自动同步。其中许多默认值可以通过向构造函数传入额外参数来定制。FieldPanel 的所有参数都受支持，包括自定义小部件。更多细节见 [面板定制](#customizing-panels)。

<a id="customizing-panels"></a>

## 面板定制

通过为面板/字段定义添加额外参数，你可以大量控制字段在 Wagtail 页面编辑界面中的显示方式。Wagtail 的页面编辑界面从 Django 管理后台继承了大部分行为，因此你会在那里找到许多定制选项。
（见 [Django 模型字段参考](https://docs.djangoproject.com/en/stable/ref/models/fields/)）。

<a id="customizing-panel-icons"></a>

### 图标

使用面板构造函数的 `icon` 参数可以覆盖显示在面板标题旁的图标。可用图标列表见 [可用图标](../advanced_topics/icons.html.md#available-icons)。

### 标题

使用面板构造函数的 `heading` 参数可以设置面板的标题。它会用于输入框的标签，并显示在内容小地图上。如果 `FieldPanel` 未设置该参数，则会用表单字段的标签自动设置（该标签又取自模型字段的 `verbose_name`）。

### CSS 类

使用面板构造函数的 `classname` 参数可以向面板添加 CSS 类。该类会被应用到面板的 HTML `<section>` 元素上。这可用于给面板添加额外样式，或控制其行为。

`title` 类可以用更大的字号和字重让输入框更醒目。

<a id="collapsible"></a>

`collapsed` 类会让编辑页面加载时把面板折叠在其标题下。

```python
content_panels = [
    MultiFieldPanel(
        [
            FieldPanel("cover"),
            FieldPanel("book_file"),
            FieldPanel("publisher"),
        ],
        heading="Collection of Book Fields",
        classname="collapsed",
    ),
]
```

### 帮助文本

使用面板构造函数的 `help_text` 参数可以定制显示在输入框上方的帮助文本。如果 `FieldPanel` 未设置，则会用表单字段的 `help_text` 自动设置（该值又取自模型字段的 `help_text`）。

### 占位符文本

默认情况下，Wagtail 用字段的标签作为占位符文本。要改变它，请给 `FieldPanel` 传入一个设置了占位符属性的小部件，其值为你想要的文本。你可以从 [Django 的表单小部件](https://docs.djangoproject.com/en/stable/ref/forms/widgets/)中选取，也可以使用 `wagtail.admin.widgets` 中的任何 Wagtail 小部件。

例如，为 `Book` Snippet 模型定制占位符：

```python
# models.py
from django import forms  # Django 的默认小部件都在这里
from wagtail.admin import widgets  # 以使用 Wagtail 特有的日期时间小部件


class Book(models.Model):
    title = models.CharField(max_length=256)
    release_date = models.DateField()
    price = models.DecimalField(max_digits=5, decimal_places=2)

    # 可以分别创建它们
    title_widget = forms.TextInput(attrs={"placeholder": "Enter Full Title"})
    # 为你的字段类型和期望效果选用正确的小部件
    date_widget = widgets.AdminDateInput(attrs={"placeholder": "dd-mm-yyyy"})

    panels = [
        TitleFieldPanel("title", widget=title_widget),  # 然后以变量的形式加入
        FieldPanel("release_date", widget=date_widget),
        FieldPanel(
            "price",
            widget=forms.NumberInput(attrs={"placeholder": "Retail price on release"}),
        ),  # 或者直接内联写
    ]
```

### 必填字段

要让某个字段的输入或选择器选择成为强制项，请在其模型定义中加上 [`blank=False`](https://docs.djangoproject.com/en/stable/ref/models/fields/#django.db.models.Field.blank)。

### 隐藏字段

在没有顶层面板定义时，会为模型中的每个字段构造一个 `FieldPanel`。如果你想在 Wagtail 页面编辑器中隐藏某个字段，请用 [`editable=False`](https://docs.djangoproject.com/en/stable/ref/models/fields/#django.db.models.Field.editable) 定义该字段。如果某个字段未出现在面板定义中，它也会被隐藏。

<a id="panels-permissions"></a>

### 权限

大多数面板可以接受 `permission` 关键字参数，从而把整组面板或特定面板限制在一组权限之下。
关于在 Wagtail 中使用权限的细节，见 [权限](../topics/permissions.html.md#permissions-overview)。

在这个示例中，'notes' 对所有编辑者可见，'cost' 和 'details' 只对拥有 `submit` 权限的人可见，'budget approval' 仅对超级用户可见。注意超级用户可访问所有字段。

```python
content_panels = [
    FieldPanel("notes"),
    MultiFieldPanel(
        [
            FieldPanel("cost"),
            FieldPanel("details"),
        ],
        heading="Budget details",
        classname="collapsed",
        permission="submit",
    ),
    FieldPanel("budget_approval", permission="superuser"),
]
```

<a id="panels-attrs"></a>

### 额外的 HTML 属性

使用 `attrs` 参数可以向面板的 HTML 元素添加自定义属性。这让你可以指定额外属性，例如 `data-*` 属性。`attrs` 参数接受一个字典，其键是属性名，渲染方式与 Django 的小部件 [`attrs`](https://docs.djangoproject.com/en/stable/ref/forms/widgets/#django.forms.Widget.attrs) 相同，其中 `True` 和 `False` 会被当作 HTML5 布尔属性处理。

例如，你可以用 `attrs` 参数把你的 Stimulus 控制器集成到面板中：

```python
content_panels = [
    MultiFieldPanel(
        [
            FieldPanel("cover"),
            FieldPanel("book_file"),
            FieldPanel("publisher", attrs={"data-my-controller-target": "myTarget"}),
        ],
        heading="Collection of Book Fields",
        classname="collapsed",
        attrs={"data-controller": "my-controller"},
    ),
]
```

<a id="panels-api"></a>

## 面板 API

本文档描述用于渲染 Wagtail 面板的基础 `Panel` 和 `BoundPanel` 类的参考 API。可用面板类型及其用法见 [内置字段与选择器](#editing-api)。

### `Panel`

### *class* wagtail.admin.panels.Panel(heading='', classname='', help_text='', base_form_class=None, icon='', attrs=None)

Defines part (or all) of the edit form interface for pages and other models
within the Wagtail admin. Each model has an associated top-level panel definition
(also known as an edit handler), consisting of a nested structure of `Panel` objects.
This provides methods for obtaining a [`ModelForm`](https://docs.djangoproject.com/en/stable/topics/forms/modelforms/#django.forms.ModelForm) subclass,
with the field list and other parameters collated from all panels in the structure.
It then handles rendering that form as HTML.

The following parameters can be used to customize how the panel is displayed.
For more details, see [面板定制](#customizing-panels).

* **参数:**
  * **heading** -- The heading text to display for the panel.
  * **classname** -- A CSS class name to add to the panel's HTML element.
  * **help_text** -- Help text to display within the panel.
  * **base_form_class** -- The base form class to use for the panel. Defaults to the model's `base_form_class`, before falling back to [`WagtailAdminModelForm`](../advanced_topics/customization/page_editing_interface.html.md#wagtail.admin.forms.WagtailAdminModelForm). This is only relevant for the top-level panel.
  * **icon** -- The name of the icon to display next to the panel heading.
  * **attrs** -- A dictionary of HTML attributes to add to the panel's HTML element.

#### bind_to_model(model)

Create a clone of this panel definition with a `model` attribute pointing to the linked model class.

#### on_model_bound()

Called after the panel has been associated with a model class and the `self.model` attribute is available;
panels can override this method to perform additional initialisation related to the model.

#### clone()

Create a clone of this panel definition. By default, constructs a new instance, passing the
keyword arguments returned by `clone_kwargs`.

#### clone_kwargs()

Return a dictionary of keyword arguments that can be used to create a clone of this panel definition.

#### get_form_options()

Return a dictionary of attributes such as 'fields', 'formsets' and 'widgets'
which should be incorporated into the form class definition to generate a form
that this panel can use.
This will only be called after binding to a model (i.e. self.model is available).

#### get_form_class()

Construct a form class that has all the fields and formsets named in
the children of this edit handler.

#### get_bound_panel(instance=None, request=None, form=None, prefix='panel')

Return a `BoundPanel` instance that can be rendered onto the template as a component. By default, this creates an instance
of the panel class's inner `BoundPanel` class, which must inherit from `Panel.BoundPanel`.

#### *property* clean_name

A name for this panel, consisting only of ASCII alphanumerics and underscores, suitable for use in identifiers.
Usually generated from the panel heading. Note that this is not guaranteed to be unique or non-empty; anything
making use of this and requiring uniqueness should validate and modify the return value as needed.

### `BoundPanel`

### *class* wagtail.admin.panels.Panel.BoundPanel(panel, instance, request, form, prefix)

A template component for a panel that has been associated with a model instance, form, and request.

除了标准的模板组件功能（见 [创建组件](../extending/template_components.html.md#creating-template-components)），它还提供下列属性与方法：

#### panel

The panel definition corresponding to this bound panel

#### instance

The model instance associated with this panel

#### request

The request object associated with this panel

#### form

The form object associated with this panel

#### prefix

A unique prefix for this panel, for use in HTML IDs

#### id_for_label()

Returns an HTML ID to be used as the target for any label referencing this panel.

#### is_shown()

Whether this panel should be rendered; if false, it is skipped in the template output.
