StreamField 区块参考

本文详述 Wagtail 提供、可供 StreamField 使用的区块类型,以及它们如何组合成新的区块类型。

备注

虽然区块定义看起来与模型字段相似,但它们不是一回事。区块只在 StreamField 内部有效 —— 用它们代替模型字段是行不通的。

class wagtail.fields.StreamField(block_types, blank=False, min_num=None, max_num=None, block_counts=None, collapsed=False)

用于把长篇内容表示为一系列不同类型内容区块的模型字段。见 如何使用 StreamField 处理混合内容。

参数:
  • block_types -- 一组区块类型,以 (name, block_definition) 元组列表的形式传入,或以 StreamBlock 实例传入。

  • blank -- 为 false(默认)时,该字段必须至少提供一个区块才算有效。

  • min_num -- 该 stream 必须拥有的子区块的最少数量。

  • max_num -- 该 stream 可以拥有的子区块的最多数量。

  • block_counts -- 指定每种区块类型的最小与最大数量,是一个把区块名映射到含(可选)``min_num`` 和 max_num 字段的字典的字典。

  • collapsed -- 为 true 时,所有区块初始都处于折叠状态。

body = StreamField(
    [
        ("heading", blocks.CharBlock(form_classname="title")),
        ("paragraph", blocks.RichTextBlock()),
        ("image", ImageBlock()),
    ],
    block_counts={
        "heading": {"min_num": 1},
        "image": {"max_num": 5},
    },
)

区块选项与方法

所有区块定义都接受以下可选关键字参数或 Meta 类属性:

  • default

    • 新的「空」区块应取得的默认值(或返回该值的可调用对象)。

  • label

    • 在编辑界面中指代该区块时显示的标签 —— 默认是区块名美化后的版本(在未指定名称的上下文中,例如 ListBlock 内,则是空字符串)。

  • icon

    • 在编辑器中为该区块类型显示的图标名称。更多细节见我们的图标总览。

  • template

    • 用于在前端渲染该区块的 Django 模板路径。见模板渲染

  • group

    • 用于把该区块归类的分组。任何分组名相同的区块都会在编辑界面中一起显示,并以该分组名作为标题。

StreamField 区块可以有预览,预览会显示在区块选择器中。为支持该特性,所有区块定义还接受以下选项:

  • preview_value

    • 用于渲染预览的占位值(或返回该值的可调用对象)。更多细节见 get_preview_value()。

  • preview_template

  • description

所有区块定义都有以下可以覆盖的方法与属性:

class wagtail.blocks.Block(*args, **kwargs)
get_context(value, parent_context=None)

Return a dict of context variables (derived from the block value and combined with the parent_context) to be used as the template context when rendering this value through a template. See the usage example for more details.

get_template(value=None, context=None)

Return the template to use for rendering the block if specified. This method allows for dynamic templates based on the block instance and a given value. See the usage example for more details.

get_preview_value()

Return the placeholder value that will be used for rendering the block's preview. By default, the value is the preview_value from the block's options if provided. If it's a callable, it will be evaluated at runtime. If preview_value is not provided, the default is used as fallback. This method can also be overridden to provide a dynamic preview value.

get_preview_context(value, parent_context=None)

Return a dict of context variables to be used as the template context when rendering the block's preview. The value argument is the value returned by get_preview_value(). The parent_context argument contains the following variables:

  • request: The current request object.

  • block_def: The block instance.

  • block_class: The block class.

  • bound_block: A BoundBlock instance representing the block and its value.

If the global preview template is used, the block will be rendered as the main content using {% include_block %}, which in turn uses get_context(). As a result, the context returned by this method will be available as the parent_context for get_context() when the preview is rendered.

get_preview_template(value, context=None)

Return the template to use for rendering the block's preview. The value argument is the value returned by get_preview_value(). The context argument contains the variables listed for the parent_context argument of get_preview_context() above (and not the context returned by that method itself).

Note that the preview template is used to render a complete HTML page of the preview, not just an HTML fragment for the block. The method returns the preview_template attribute from the block's options if provided, and falls back to the global preview template otherwise.

If the global preview template is used, the block will be rendered as the main content using {% include_block %}, which in turn uses get_template().

get_description()

Return the description of the block to be shown to editors as part of the preview. For field block types, it will fall back to help_text if not provided.

clean(value)

Validate value and return a cleaned version of it, or throw a ValidationError if validation fails.

To determine whether to defer any validation that is not required for saving a draft, the is_deferred_validation attribute can be checked.

For more details on how to implement custom validation logic, refer to StreamField 校验.

is_previewable

Determine whether the block is previewable in the block picker. By default, it automatically detects when a custom template is used or the the global preview template is overridden and a preview value is provided. If the block is previewable by other means, override this property to return True. To turn off previews for the block, set it to False.

is_deferred_validation

Indicates whether this block is currently in a state where any validation that is not required for saving a draft should be deferred.

字段区块类型

class wagtail.blocks.FieldBlock(*args, **kwargs)

基类:Block

A block that wraps a Django form field

所有 StreamField 字段区块类型的父类。

除标准可选关键字参数或 Meta 类属性之外,字段区块还接受:

参数:

required_on_save -- 该字段在保存为草稿时是否应强制执行必填约束,类似于 FieldPanel.required_on_save。默认为 False。

class wagtail.blocks.CharBlock(*args, **kwargs)

基类:FieldBlock

单行文本输入。除标准参数之外,还接受以下关键字参数:

参数:
  • required -- 为 true(默认)时,该字段不能留空。

  • max_length -- 该字段允许的最大长度。

  • min_length -- 该字段允许的最小长度。

  • help_text -- 与字段一同显示的帮助文本。

  • search_index -- 为 false(默认 true)时,该区块的内容不会被加入搜索索引。

  • validators -- 该字段的校验函数列表(见 Django 校验器)。

  • form_classname -- 在页面编辑表单中渲染时,加到该表单字段 class 属性上的值。

  • form_attrs -- 在页面编辑表单中渲染时,加到该表单字段包裹元素上的额外属性字典。

class wagtail.blocks.TextBlock(*args, **kwargs)

基类:FieldBlock

多行文本输入。与 CharBlock 一样,除标准参数之外还接受以下关键字参数:

参数:
  • required -- 为 true(默认)时,该字段不能留空。

  • max_length -- 该字段允许的最大长度。

  • min_length -- 该字段允许的最小长度。

  • help_text -- 与字段一同显示的帮助文本。

  • search_index -- 为 false(默认 true)时,该区块的内容不会被加入搜索索引。

  • rows -- 文本域上显示的行数(默认为 1)。

  • validators -- 该字段的校验函数列表(见 Django 校验器)。

  • form_classname -- 在页面编辑表单中渲染时,加到该表单字段 class 属性上的值。

  • form_attrs -- 在页面编辑表单中渲染时,加到该表单字段包裹元素上的额外属性字典。

class wagtail.blocks.EmailBlock(*args, **kwargs)

基类:FieldBlock

单行邮箱输入,会校验该值是否为合法的电子邮箱地址。除标准参数之外,还接受以下关键字参数:

参数:
  • required -- 为 true(默认)时,该字段不能留空。

  • help_text -- 与字段一同显示的帮助文本。

  • validators -- 该字段的校验函数列表(见 Django 校验器)。

  • form_classname -- 在页面编辑表单中渲染时,加到该表单字段 class 属性上的值。

  • form_attrs -- 在页面编辑表单中渲染时,加到该表单字段包裹元素上的额外属性字典。

class wagtail.blocks.IntegerBlock(*args, **kwargs)

基类:FieldBlock

单行整数输入,会校验该值是否为合法的整数。除标准参数之外,还接受以下关键字参数:

参数:
  • required -- 为 true(默认)时,该字段不能留空。

  • max_value -- 该字段允许的最大数值。

  • min_value -- 该字段允许的最小数值。

  • help_text -- 与字段一同显示的帮助文本。

  • validators -- 该字段的校验函数列表(见 Django 校验器)。

  • form_classname -- 在页面编辑表单中渲染时,加到该表单字段 class 属性上的值。

  • form_attrs -- 在页面编辑表单中渲染时,加到该表单字段包裹元素上的额外属性字典。

class wagtail.blocks.FloatBlock(*args, **kwargs)

基类:FieldBlock

单行 Float 输入,会校验该值是否为合法的浮点数。除标准参数之外,还接受以下关键字参数:

参数:
  • required -- 为 true(默认)时,该字段不能留空。

  • max_value -- 该字段允许的最大数值。

  • min_value -- 该字段允许的最小数值。

  • help_text -- 与字段一同显示的帮助文本。

  • validators -- 该字段的校验函数列表(见 Django 校验器)。

  • form_classname -- 在页面编辑表单中渲染时,加到该表单字段 class 属性上的值。

  • form_attrs -- 在页面编辑表单中渲染时,加到该表单字段包裹元素上的额外属性字典。

class wagtail.blocks.DecimalBlock(*args, **kwargs)

基类:FieldBlock

单行小数输入,会校验该值是否为合法的小数。除标准参数之外,还接受以下关键字参数:

参数:
  • required -- 为 true(默认)时,该字段不能留空。

  • help_text -- 与字段一同显示的帮助文本。

  • max_value -- 该字段允许的最大数值。

  • min_value -- 该字段允许的最小数值。

  • max_digits -- 该数字允许的最大位数。该数值必须大于或等于 decimal_places。

  • decimal_places -- 该数字要存储的小数位数。

  • validators -- 该字段的校验函数列表(见 Django 校验器)。

  • form_classname -- 在页面编辑表单中渲染时,加到该表单字段 class 属性上的值。

  • form_attrs -- 在页面编辑表单中渲染时,加到该表单字段包裹元素上的额外属性字典。

class wagtail.blocks.RegexBlock(*args, **kwargs)

基类:FieldBlock

单行文本输入,会用正则表达式校验字符串。用于校验的正则表达式必须作为第一个参数,或作为关键字参数 regex 提供。

blocks.RegexBlock(regex=r'^[0-9]{3}$', error_messages={
    'invalid': "Not a valid library card number."
})

除标准参数之外,还接受以下关键字参数:

参数:
  • regex -- 用于校验的正则表达式。

  • error_messages -- 错误信息字典,包含 required (值为空时显示的信息)和 invalid (值不匹配时显示的信息)两个键中的一个或两个。

  • required -- 为 true(默认)时,该字段不能留空。

  • help_text -- 与字段一同显示的帮助文本。

  • max_length -- 该字段允许的最大长度。

  • min_length -- 该字段允许的最小长度。

  • validators -- 该字段的校验函数列表(见 Django 校验器)。

  • form_classname -- 在页面编辑表单中渲染时,加到该表单字段 class 属性上的值。

  • form_attrs -- 在页面编辑表单中渲染时,加到该表单字段包裹元素上的额外属性字典。

class wagtail.blocks.URLBlock(*args, **kwargs)

基类:FieldBlock

单行文本输入,会校验该字符串是否为合法 URL。除标准参数之外,还接受以下关键字参数:

参数:
  • required -- 为 true(默认)时,该字段不能留空。

  • max_length -- 该字段允许的最大长度。

  • min_length -- 该字段允许的最小长度。

  • help_text -- 与字段一同显示的帮助文本。

  • validators -- 该字段的校验函数列表(见 Django 校验器)。

  • form_classname -- 在页面编辑表单中渲染时,加到该表单字段 class 属性上的值。

  • form_attrs -- 在页面编辑表单中渲染时,加到该表单字段包裹元素上的额外属性字典。

class wagtail.blocks.BooleanBlock(*args, **kwargs)

基类:FieldBlock

一个复选框。除标准参数之外,还接受以下关键字参数:

参数:
  • required -- 为 true(默认)时,必须勾选该复选框才能继续。与 Django 的 BooleanField 一样,可以留作勾选或不勾选的复选框必须显式地标为 required=False。

  • help_text -- 与字段一同显示的帮助文本。

  • form_classname -- 在页面编辑表单中渲染时,加到该表单字段 class 属性上的值。

  • form_attrs -- 在页面编辑表单中渲染时,加到该表单字段包裹元素上的额外属性字典。

class wagtail.blocks.DateBlock(*args, **kwargs)

基类:FieldBlock

一个日期选择器。除标准参数之外,还接受以下关键字参数:

参数:
  • format -- 日期格式。必须是 DATE_INPUT_FORMATS 设置中列出的已认可格式之一。若未指定,Wagtail 会使用 WAGTAIL_DATE_FORMAT 设置,回退值为 "%Y-%m-%d"。

  • required -- 为 true(默认)时,该字段不能留空。

  • help_text -- 与字段一同显示的帮助文本。

  • validators -- 该字段的校验函数列表(见 Django 校验器)。

  • form_classname -- 在页面编辑表单中渲染时,加到该表单字段 class 属性上的值。

  • form_attrs -- 在页面编辑表单中渲染时,加到该表单字段包裹元素上的额外属性字典。

class wagtail.blocks.TimeBlock(*args, **kwargs)

基类:FieldBlock

一个时间选择器。除标准参数之外,还接受以下关键字参数:

参数:
  • format -- 时间格式。必须是 TIME_INPUT_FORMATS 设置中列出的已认可格式之一。若未指定,Wagtail 会使用 WAGTAIL_TIME_FORMAT 设置,回退值为 "%H:%M"。

  • required -- 为 true(默认)时,该字段不能留空。

  • help_text -- 与字段一同显示的帮助文本。

  • validators -- 该字段的校验函数列表(见 Django 校验器)。

  • form_classname -- 在页面编辑表单中渲染时,加到该表单字段 class 属性上的值。

  • form_attrs -- 在页面编辑表单中渲染时,加到该表单字段包裹元素上的额外属性字典。

class wagtail.blocks.DateTimeBlock(*args, **kwargs)

基类:FieldBlock

一个日期/时间组合选择器。除标准参数之外,还接受以下关键字参数:

参数:
  • format -- 日期/时间格式。必须是 DATETIME_INPUT_FORMATS 设置中列出的已认可格式之一。若未指定,Wagtail 会使用 WAGTAIL_DATETIME_FORMAT 设置,回退值为 "%Y-%m-%d %H:%M"。

  • required -- 为 true(默认)时,该字段不能留空。

  • help_text -- 与字段一同显示的帮助文本。

  • validators -- 该字段的校验函数列表(见 Django 校验器)。

  • form_classname -- 在页面编辑表单中渲染时,加到该表单字段 class 属性上的值。

  • form_attrs -- 在页面编辑表单中渲染时,加到该表单字段包裹元素上的额外属性字典。

class wagtail.blocks.RichTextBlock(*args, **kwargs)

基类:FieldBlock

用于创建带格式文本(包括链接、粗体/斜体等)的所见即所得编辑器。除标准参数之外,还接受以下关键字参数:

参数:
  • editor -- 要使用的富文本编辑器(见 WAGTAILADMIN_RICH_TEXT_EDITORS)。

  • features -- 指定允许的特性集合(见 限制富文本字段中的特性)。

  • required -- 为 true(默认)时,该字段不能留空。

  • max_length -- 该字段允许的最大长度。只统计文本;富文本格式、嵌入内容以及段落/换行都不计入上限。

  • min_length -- 该字段允许的最小长度。只统计文本;富文本格式、嵌入内容以及段落/换行都不计入上限。

  • search_index -- 为 false(默认 true)时,该区块的内容不会被加入搜索索引。

  • help_text -- 与字段一同显示的帮助文本。

  • validators -- 该字段的校验函数列表(见 Django 校验器)。

  • form_classname -- 在页面编辑表单中渲染时,加到该表单字段 class 属性上的值。

  • form_attrs -- 在页面编辑表单中渲染时,加到该表单字段包裹元素上的额外属性字典。

class wagtail.blocks.RawHTMLBlock(*args, **kwargs)

基类:FieldBlock

用于输入原始 HTML 的文本区域,这些 HTML 会在页面输出中不经转义地渲染。除标准参数之外,还接受以下关键字参数:

参数:
  • required -- 为 true(默认)时,该字段不能留空。

  • max_length -- 该字段允许的最大长度。

  • min_length -- 该字段允许的最小长度。

  • help_text -- 与字段一同显示的帮助文本。

  • validators -- 该字段的校验函数列表(见 Django 校验器)。

  • form_classname -- 在页面编辑表单中渲染时,加到该表单字段 class 属性上的值。

  • form_attrs -- 在页面编辑表单中渲染时,加到该表单字段包裹元素上的额外属性字典。

警告

使用该区块时,无法阻止编辑者向页面插入恶意脚本,包括那些在另一位管理员查看页面时让该编辑者取得管理员权限的脚本。除非你的编辑者完全可信,否则不要使用该区块。

class wagtail.blocks.BlockQuoteBlock(*args, **kwargs)

基类:TextBlock

一个文本字段,其内容会在页面输出中被包在一对 HTML <blockquote> 标签中。除标准参数之外,还接受以下关键字参数:

参数:
  • required -- 为 true(默认)时,该字段不能留空。

  • max_length -- 该字段允许的最大长度。

  • min_length -- 该字段允许的最小长度。

  • help_text -- 与字段一同显示的帮助文本。

  • validators -- 该字段的校验函数列表(见 Django 校验器)。

  • form_classname -- 在页面编辑表单中渲染时,加到该表单字段 class 属性上的值。

  • form_attrs -- 在页面编辑表单中渲染时,加到该表单字段包裹元素上的额外属性字典。

class wagtail.blocks.ChoiceBlock(*args, **kwargs)

基类:BaseChoiceBlock

用于从选项列表中选择一项的下拉选择框。除标准参数之外,还接受以下关键字参数:

参数:
  • choices -- 一组选项,格式可为 Django 模型字段 choices 参数所接受的任何格式,也可以是返回这类列表的可调用对象。

  • required -- 为 true(默认)时,该字段不能留空。

  • help_text -- 与字段一同显示的帮助文本。

  • search_index -- 为 false(默认 true)时,该区块的内容不会被加入搜索索引。

  • widget -- 用于渲染该字段的表单小部件(见 Django 小部件)。

  • validators -- 该字段的校验函数列表(见 Django 校验器)。

  • form_classname -- 在页面编辑表单中渲染时,加到该表单字段 class 属性上的值。

  • form_attrs -- 在页面编辑表单中渲染时,加到该表单字段包裹元素上的额外属性字典。

ChoiceBlock 也可以被继承,从而产生一个在所有使用处都共享同一选项列表的可复用区块。例如,这样的区块定义:

blocks.ChoiceBlock(choices=[
    ('tea', 'Tea'),
    ('coffee', 'Coffee'),
], icon='cup')

可以改写为 ChoiceBlock 的子类:

class DrinksChoiceBlock(blocks.ChoiceBlock):
    choices = [
        ('tea', 'Tea'),
        ('coffee', 'Coffee'),
    ]

    class Meta:
        icon = 'cup'

StreamField 定义随后就可以用 DrinksChoiceBlock() 代替完整的 ChoiceBlock 定义。注意,这只在 choices 是固定列表时有效,不能是可调用对象。

class wagtail.blocks.MultipleChoiceBlock(*args, **kwargs)

基类:BaseChoiceBlock

用于从选项列表中选择多项的选择框。除标准参数之外,还接受以下关键字参数:

参数:
  • choices -- 一组选项,格式可为 Django 模型字段 choices 参数所接受的任何格式,也可以是返回这类列表的可调用对象。

  • required -- 为 true(默认)时,该字段不能留空。

  • help_text -- 与字段一同显示的帮助文本。

  • search_index -- 为 false(默认 true)时,该区块的内容不会被加入搜索索引。

  • widget -- 用于渲染该字段的表单小部件(见 Django 小部件)。

  • validators -- 该字段的校验函数列表(见 Django 校验器)。

  • form_classname -- 在页面编辑表单中渲染时,加到该表单字段 class 属性上的值。

  • form_attrs -- 在页面编辑表单中渲染时,加到该表单字段包裹元素上的额外属性字典。

class wagtail.blocks.PageChooserBlock(*args, **kwargs)

基类:ChooserBlock

用于选择页面对象的控件,使用 Wagtail 的页面浏览器。除标准参数之外,还接受以下关键字参数:

参数:
  • required -- 为 true(默认)时,该字段不能留空。

  • page_type -- 把可选范围限制为一种或多种特定页面类型;默认情况下可选任何页面类型。可以指定为页面模型类、模型名(字符串),或它们的列表或元组。

  • can_choose_root -- 默认为 false。为 true 时,编辑者可以把树根选作页面。通常这并不可取,因为树根从来不是可用的页面,但在某些特殊情形下可能合适。例如,一个提供相关文章流的区块,可以用 PageChooserBlock 选择从站点的哪个子栏目取文章,而根对应「全部位置」。

class wagtail.documents.blocks.DocumentChooserBlock(*args, **kwargs)

基类:BaseDocumentChooserBlock

让编辑者选择已有文档对象或上传新文档的控件。还接受以下额外关键字参数:

参数:

required -- 为 true(默认)时,该字段不能留空。

class wagtail.images.blocks.ImageBlock(*args, **kwargs)

基类:StructBlock

An usage of ImageChooserBlock with support for alt text. For backward compatibility, this block overrides necessary methods to change the StructValue to be an Image model instance, making it compatible in places where ImageChooserBlock was used.

一个以无障碍为重的控件,让编辑者选择已有图片或上传新图片。它为添加替代文本、以及标记图片是否纯属装饰提供了支持,是 Wagtail 推荐的图片上传方式。还接受以下额外关键字参数:

参数:

required -- 为 true(默认)时,该字段不能留空。

ImageBlock 兼顾了对 ImageChooserBlock 的向后兼容。最初定义为 ImageChooserBlock 的区块可以直接替换为 ImageBlock —— 用 ImageChooserBlock 创建的既有数据会被自动处理,并在该字段重新保存时转换为 ImageBlock 的数据格式。

class wagtail.images.blocks.ImageChooserBlock(*args, **kwargs)

基类:ChooserBlock

让编辑者选择已有图片或上传新图片的控件。还接受以下额外关键字参数:

参数:

required -- 为 true(默认)时,该字段不能留空。

class wagtail.snippets.blocks.SnippetChooserBlock(*args, **kwargs)

基类:ChooserBlock

让编辑者选择 Snippet 对象的控件。必须传入一个位置参数:要从中选择的 Snippet 类。还接受以下额外关键字参数:

参数:

required -- 为 true(默认)时,该字段不能留空。

class wagtail.embeds.blocks.EmbedBlock(*args, **kwargs)

基类:URLBlock

供编辑者输入媒体条目(例如 YouTube 视频)URL 的字段,使其作为嵌入媒体出现在页面上。除标准参数之外,还接受以下关键字参数:

参数:
  • required -- 为 true(默认)时,该字段不能留空。

  • max_width -- 嵌入内容的最大宽度(像素);请求嵌入时会被传给提供方。

  • max_height -- 嵌入内容的最大高度(像素);请求嵌入时会被传给提供方。:param max_length: 该字段允许的最大长度。

  • min_length -- 该字段允许的最小长度。

  • help_text -- 与字段一同显示的帮助文本。

结构性区块类型

class wagtail.blocks.StaticBlock(*args, **kwargs)

基类:Block

A block that just 'exists' and has no fields.

一个没有任何字段的区块,因此在渲染时不会向模板传递任何特定值。如果你需要让编辑者插入一些始终相同、或无需在页面编辑器中配置的内容(例如地址、第三方服务的嵌入代码,或模板使用了模板标签的较复杂代码片段),这会很有用。还接受以下额外关键字参数:

参数:

admin_text -- 使用该区块时在管理后台中显示的文本字符串。默认情况下,编辑界面中会显示一些默认文本(如果你传了 label 关键字参数,其中会包含它),以免该区块看起来是空的,但这可以通过传入 admin_text 来定制:

blocks.StaticBlock(
    admin_text='Latest posts: no configuration needed.',
    # or admin_text=mark_safe('<b>Latest posts</b>: no configuration needed.'),
    template='latest_posts.html')

StaticBlock 也可以被继承,从而产生一个在所有使用处都共享同一配置的可复用区块:

class LatestPostsStaticBlock(blocks.StaticBlock):
    class Meta:
        icon = 'user'
        label = 'Latest posts'
        admin_text = '{label}: configured elsewhere'.format(label=label)
        template = 'latest_posts.html'
        form_attrs = {
            'data-controller': 'magic',
            'data-action': 'click->magic#abracadabra',
        }
class wagtail.blocks.StructBlock(*args, **kwargs)

基类:BaseStructBlock

由一组固定的子区块组成、一起显示的区块。第一个参数接受一组 (name, block_definition) 元组:

body = StreamField([
    # ...
    ('person', blocks.StructBlock([
        ('first_name', blocks.CharBlock()),
        ('surname', blocks.CharBlock()),
        ('photo', ImageBlock(required=False)),
        ('biography', blocks.RichTextBlock()),
    ], icon='user')),
])

另一种做法是继承 StructBlock,指定一组可复用的子区块:

class PersonBlock(blocks.StructBlock):
    first_name = blocks.CharBlock()
    surname = blocks.CharBlock()
    photo = ImageBlock(required=False)
    biography = blocks.RichTextBlock()

    class Meta:
        icon = 'user'

Meta 类支持 default、label、icon 和 template 属性,其含义与把它们传给区块构造函数时相同。

这样就把 PersonBlock() 定义为可在 StreamField 定义中使用的区块类型:

body = StreamField([
    ('heading', blocks.CharBlock(form_classname="title")),
    ('paragraph', blocks.RichTextBlock()),
    ('image', ImageBlock()),
    ('person', PersonBlock()),
])

以下额外选项既可作为关键字参数,也可作为 Meta 类属性使用:

参数:
  • form_classname -- 在编辑界面中显示时,设置在该区块根元素上的 HTML class 属性,默认为 struct-block。覆盖时,如果你有自定义代码或使用了依赖它的第三方包,可能需要保留默认的 struct-block 类。见 添加自定义类和属性。

  • form_attrs -- 在编辑界面中显示时,设置在该区块根元素上的额外属性字典。见 添加自定义类和属性。

  • form_template -- 用于渲染该区块表单的 Django 模板路径。见 定制 StructBlock 表单的模板。

  • collapsed -- 为 true 且该区块位于另一个 StructBlock 内时,该区块初始处于折叠状态。对于子区块很多、或不预期被频繁编辑的区块,这可能有用。见 定制初始折叠状态。

  • value_class -- 用作该区块返回值类型的 wagtail.blocks.StructValue 子类。见 StructBlock 值上的额外方法与属性。

  • search_index -- 为 false(默认 true)时,该区块的内容不会被加入搜索索引。

  • label_format -- 决定在编辑界面中该区块被折叠时,显示在 label 之后的摘要标签。默认显示 StructBlock 中第一个子区块的值,但可以在此设置一个含大括号包裹的区块名的字符串来定制 —— 例如 label_format = "{surname}, {first_name}"。如果你希望完全隐藏摘要标签,请把它设为空字符串 ""。

  • form_layout -- 一组区块名或 BlockGroup 实例,用于决定子区块在编辑界面中的显示顺序。另一种做法是提供 BlockGroup 实例代替列表,以定义一组 children 和 settings 区块。更多细节见 改变子区块的顺序与分组 和 BlockGroup。

get_form_layout() → BlockGroup

Return the BlockGroup representing the form layout for this StructBlock.

get_api_representation(value, context=None)

Recursively call get_api_representation on children and return as a plain dict

更多信息见 API 中的 StreamField 区块。

class wagtail.blocks.ListBlock(*args, **kwargs)

基类:Block

由许多同类型子区块组成的区块。编辑者可以添加不限数量的子区块,并重新排序和删除。第一个参数接受子区块的定义:

body = StreamField([
    # ...
    ('ingredients_list', blocks.ListBlock(blocks.CharBlock(label="Ingredient"))),
])

任何区块类型都可以作为子区块类型,包括结构性类型:

body = StreamField([
    # ...
    ('ingredients_list', blocks.ListBlock(blocks.StructBlock([
        ('ingredient', blocks.CharBlock()),
        ('amount', blocks.CharBlock(required=False)),
    ]))),
])

以下额外选项既可作为关键字参数,也可作为 Meta 类属性使用:

参数:
  • form_classname -- 在编辑界面中显示时,设置在该区块根元素上的 HTML class 属性。

  • form_attrs -- 在编辑界面中显示时,设置在该区块根元素上的额外属性字典。

  • min_num -- 该列表必须拥有的子区块的最少数量。

  • max_num -- 该列表可以拥有的子区块的最多数量。

  • search_index -- 为 false(默认 true)时,该区块的内容不会被加入搜索索引。

  • collapsed -- 为 true 时,所有子区块初始都处于折叠状态。

class wagtail.blocks.StreamBlock(*args, **kwargs)

基类:BaseStreamBlock

由一系列不同类型的子区块组成的区块,这些子区块可以任意混合与重排。它被用作 StreamField 本身的整体机制,但也可以嵌套、或在其它结构性区块类型内使用。第一个参数接受一组 (name, block_definition) 元组:

body = StreamField([
    # ...
    ('carousel', blocks.StreamBlock(
        [
            ('image', ImageBlock()),
            ('quotation', blocks.StructBlock([
                ('text', blocks.TextBlock()),
                ('author', blocks.CharBlock()),
            ])),
            ('video', EmbedBlock()),
        ],
        icon='cogs'
    )),
])

与 StructBlock 一样,子区块列表也可以作为 StreamBlock 的子类提供:

class CarouselBlock(blocks.StreamBlock):
    image = ImageBlock()
    quotation = blocks.StructBlock([
        ('text', blocks.TextBlock()),
        ('author', blocks.CharBlock()),
    ])
    video = EmbedBlock()

    class Meta:
        icon='cogs'

由于 StreamField 接受 StreamBlock 实例作为参数(代替一组区块类型),这使得复用一套通用区块类型而无需重复定义成为可能:

class HomePage(Page):
    carousel = StreamField(
        CarouselBlock(max_num=10, block_counts={'video': {'max_num': 2}}),
    )

StreamBlock 接受以下额外选项,既可作为关键字参数,也可作为 Meta 属性:

参数:
  • required -- 为 true(默认)时,必须至少提供一个子区块。当把该 StreamBlock 用作 StreamField 的顶层区块时,此项会被忽略;这种情况下改为遵循 StreamField 的 blank 属性。

  • min_num -- 该 stream 必须拥有的子区块的最少数量。

  • max_num -- 该 stream 可以拥有的子区块的最多数量。

  • search_index -- 为 false(默认 true)时,该区块的内容不会被加入搜索索引。

  • block_counts -- 指定每种区块类型的最小与最大数量,是一个把区块名映射到含(可选)``min_num`` 和 max_num 字段的字典的字典。

  • collapsed -- 为 true 时,所有子区块初始都处于折叠状态。

  • form_classname -- 在编辑界面中显示时,设置在该区块根元素上的 HTML class 属性。

  • form_attrs -- 在编辑界面中显示时,设置在该区块根元素上的额外属性字典。

body = StreamField([
    # ...
    ('event_promotions', blocks.StreamBlock([
        ('hashtag', blocks.CharBlock()),
        ('post_date', blocks.DateBlock()),
    ], form_classname='event-promotions')),
])
class EventPromotionsBlock(blocks.StreamBlock):
    hashtag = blocks.CharBlock()
    post_date = blocks.DateBlock()

    class Meta:
        form_classname = 'event-promotions'

辅助组件

BlockGroup

class wagtail.blocks.BlockGroup(children: list[str | BlockGroup], settings: list[str | BlockGroup] = None, heading='', classname='', help_text='', icon='placeholder', attrs: dict | None = None, label_format: str | None = None)

A grouping of blocks within a StructBlock's form layout in the editing interface. Can be used directly as the form_layout in StructBlock.Meta, or nested within another BlockGroup.

参数:
  • children (list[str | BlockGroup]) -- A list of block names or nested BlockGroup that will be rendered in the main content area.

  • settings (list[str | BlockGroup]) -- A list of block names or nested BlockGroup that will be rendered in the collapsible "settings" area that is hidden by default.

The following attributes are only used when the BlockGroup is nested within another BlockGroup. For the top-level BlockGroup used as Meta.form_layout in a StructBlock, these attributes are ignored in favor of the corresponding attributes on StructBlock.Meta.

参数:
  • heading (str) -- The heading label of the collapsible panel for this block group. For a top-level group, the StructBlock's label will be used instead.

  • classname (str) -- Additional CSS class name(s) to add to the block group's main content area. To set the group to be initially collapsed, include the collapsed class here.

  • help_text (str) -- Help text to display below the block group's heading.

  • icon (str) -- The name of the icon to display alongside the block group's heading.

  • attrs (dict) -- A dictionary of HTML attributes to add to the block group's main content area.

  • label_format (str | None) -- The summary label shown after the heading when the block is collapsed in the editing interface. By default, the value of the first child block is shown, but this can be customized by setting a string here with block names contained in braces - for example label_format = " {surname}, {first_name}". If you wish to hide the summary label entirely, set this to the empty string "".

方法

get_sorted_block_names()

Return a flat list of all block names in this BlockGroup and any nested BlockGroups in the group's list order.