<a id="streamfield-block-reference"></a>

# StreamField block reference

This document details the block types provided by Wagtail for use in [StreamField](../../topics/streamfield.md#streamfield-topic), and how they can be combined into new block types.

#### NOTE
While block definitions look similar to model fields, they are not the same thing. Blocks are only valid within a StreamField - using them in place of a model field will not work.

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

A model field for representing long-form content as a sequence of content blocks of various types. See [How to use StreamField for mixed content](../../topics/streamfield.md#streamfield-topic).

* **Parameters:**
  * **block_types** – A list of block types, passed as either a list of `(name, block_definition)` tuples or a `StreamBlock` instance.
  * **blank** – When false (the default), at least one block must be provided for the field to be considered valid.
  * **min_num** – Minimum number of sub-blocks that the stream must have.
  * **max_num** – Maximum number of sub-blocks that the stream may have.
  * **block_counts** – Specifies the minimum and maximum number of each block type, as a dictionary mapping block names to dicts with (optional) `min_num` and `max_num` fields.
  * **collapsed** – When true, all blocks are initially collapsed.

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

## Block options and methods

All block definitions accept the following optional keyword arguments or `Meta` class attributes:

- `default`
  - The default value (or a callable that returns the value) that a new ‘empty’ block should receive.
- `label`
  - The label to display in the editor interface when referring to this block - defaults to a prettified version of the block name (or, in a context where no name is assigned - such as within a `ListBlock` - the empty string).
- `icon`
  - The name of the icon to display for this block type in the editor. For more details, see our [icons overview](../../advanced_topics/icons.md#icons).
- `template`
  - The path to a Django template that will be used to render this block on the front end. See [Template rendering](../../topics/streamfield.md#streamfield-template-rendering)
- `group`
  - The group used to categorize this block. Any blocks with the same group name will be shown together in the editor interface with the group name as a heading.

<a id="block-preview-arguments"></a>

[StreamField blocks can have previews](../../topics/streamfield.md#configuring-block-previews) that will be shown inside the block picker. To accommodate the feature, all block definitions also accept the following options:

- `preview_value`
  - The placeholder value (or a callable that returns the value) that will be used for rendering the preview. See [`get_preview_value()`](#wagtail.blocks.Block.get_preview_value) for more details.
- `preview_template`
  - The template that is used to render the preview. See [`get_preview_template()`](#wagtail.blocks.Block.get_preview_template) for more details.
- `description`
  - The description of the block to be shown to editors. See [`get_description()`](#wagtail.blocks.Block.get_description) for more details.

All block definitions have the following methods and properties that can be overridden:

### *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](../../topics/streamfield.md#streamfield-get-context) 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](../../topics/streamfield.md#streamfield-get-template) 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()`](#wagtail.blocks.Block.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](../../topics/streamfield.md#streamfield-global-preview-template)
is used, the block will be rendered as the main content using
`{% include_block %}`, which in turn uses [`get_context()`](#wagtail.blocks.Block.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()`](#wagtail.blocks.Block.get_preview_value). The `context`
argument contains the variables listed for the `parent_context` argument
of [`get_preview_context()`](#wagtail.blocks.Block.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](../../topics/streamfield.md#streamfield-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()`](#wagtail.blocks.Block.get_template).

#### get_description()

Return the description of the block to be shown to editors as part of the preview.
For [field block types](#field-block-types), it will fall back to
`help_text` if not provided.

#### 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](../../topics/streamfield.md#streamfield-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`.

<a id="field-block-types"></a>

## Field block types

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

Bases: [`Block`](#wagtail.blocks.Block)

A block that wraps a Django form field

The parent class of all StreamField field block types.

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

Bases: [`FieldBlock`](#wagtail.blocks.FieldBlock)

A single-line text input. The following keyword arguments are accepted in addition to the standard ones:

* **Parameters:**
  * **required** – If true (the default), the field cannot be left blank.
  * **max_length** – The maximum allowed length of the field.
  * **min_length** – The minimum allowed length of the field.
  * **help_text** – Help text to display alongside the field.
  * **search_index** – If false (default true), the content of this block will not be indexed for searching.
  * **validators** – A list of validation functions for the field (see [Django Validators](https://docs.djangoproject.com/en/stable/ref/validators/)).
  * **form_classname** – A value to add to the form field’s `class` attribute when rendered on the page editing form.
  * **form_attrs** – A dictionary of additional attributes to add to the form field’s wrapper element when rendered on the page editing form.

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

Bases: [`FieldBlock`](#wagtail.blocks.FieldBlock)

A multi-line text input. As with `CharBlock`, the following keyword arguments are accepted in addition to the standard ones:

* **Parameters:**
  * **required** – If true (the default), the field cannot be left blank.
  * **max_length** – The maximum allowed length of the field.
  * **min_length** – The minimum allowed length of the field.
  * **help_text** – Help text to display alongside the field.
  * **search_index** – If false (default true), the content of this block will not be indexed for searching.
  * **rows** – Number of rows to show on the textarea (defaults to 1).
  * **validators** – A list of validation functions for the field (see [Django Validators](https://docs.djangoproject.com/en/stable/ref/validators/)).
  * **form_classname** – A value to add to the form field’s `class` attribute when rendered on the page editing form.
  * **form_attrs** – A dictionary of additional attributes to add to the form field’s wrapper element when rendered on the page editing form.

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

Bases: [`FieldBlock`](#wagtail.blocks.FieldBlock)

A single-line email input that validates that the value is a valid e-mail address. The following keyword arguments are accepted in addition to the standard ones:

* **Parameters:**
  * **required** – If true (the default), the field cannot be left blank.
  * **help_text** – Help text to display alongside the field.
  * **validators** – A list of validation functions for the field (see [Django Validators](https://docs.djangoproject.com/en/stable/ref/validators/)).
  * **form_classname** – A value to add to the form field’s `class` attribute when rendered on the page editing form.
  * **form_attrs** – A dictionary of additional attributes to add to the form field’s wrapper element when rendered on the page editing form.

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

Bases: [`FieldBlock`](#wagtail.blocks.FieldBlock)

A single-line integer input that validates that the value is a valid whole number. The following keyword arguments are accepted in addition to the standard ones:

* **Parameters:**
  * **required** – If true (the default), the field cannot be left blank.
  * **max_value** – The maximum allowed numeric value of the field.
  * **min_value** – The minimum allowed numeric value of the field.
  * **help_text** – Help text to display alongside the field.
  * **validators** – A list of validation functions for the field (see [Django Validators](https://docs.djangoproject.com/en/stable/ref/validators/)).
  * **form_classname** – A value to add to the form field’s `class` attribute when rendered on the page editing form.
  * **form_attrs** – A dictionary of additional attributes to add to the form field’s wrapper element when rendered on the page editing form.

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

Bases: [`FieldBlock`](#wagtail.blocks.FieldBlock)

A single-line Float input that validates that the value is a valid floating point number. The following keyword arguments are accepted in addition to the standard ones:

* **Parameters:**
  * **required** – If true (the default), the field cannot be left blank.
  * **max_value** – The maximum allowed numeric value of the field.
  * **min_value** – The minimum allowed numeric value of the field.
  * **help_text** – Help text to display alongside the field.
  * **validators** – A list of validation functions for the field (see [Django Validators](https://docs.djangoproject.com/en/stable/ref/validators/)).
  * **form_classname** – A value to add to the form field’s `class` attribute when rendered on the page editing form.
  * **form_attrs** – A dictionary of additional attributes to add to the form field’s wrapper element when rendered on the page editing form.

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

Bases: [`FieldBlock`](#wagtail.blocks.FieldBlock)

A single-line decimal input that validates that the value is a valid decimal number. The following keyword arguments are accepted in addition to the standard ones:

* **Parameters:**
  * **required** – If true (the default), the field cannot be left blank.
  * **help_text** – Help text to display alongside the field.
  * **max_value** – The maximum allowed numeric value of the field.
  * **min_value** – The minimum allowed numeric value of the field.
  * **max_digits** – The maximum number of digits allowed in the number. This number must be greater than or equal to `decimal_places`.
  * **decimal_places** – The number of decimal places to store with the number.
  * **validators** – A list of validation functions for the field (see [Django Validators](https://docs.djangoproject.com/en/stable/ref/validators/)).
  * **form_classname** – A value to add to the form field’s `class` attribute when rendered on the page editing form.
  * **form_attrs** – A dictionary of additional attributes to add to the form field’s wrapper element when rendered on the page editing form.

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

Bases: [`FieldBlock`](#wagtail.blocks.FieldBlock)

A single-line text input that validates a string against a regular expression. The regular expression used for validation must be supplied as the first argument, or as the keyword argument `regex`.

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

The following keyword arguments are accepted in addition to the standard ones:

* **Parameters:**
  * **regex** – Regular expression to validate against.
  * **error_messages** – Dictionary of error messages, containing either or both of the keys `required` (for the message shown on an empty value) or `invalid` (for the message shown on a non-matching value).
  * **required** – If true (the default), the field cannot be left blank.
  * **help_text** – Help text to display alongside the field.
  * **max_length** – The maximum allowed length of the field.
  * **min_length** – The minimum allowed length of the field.
  * **validators** – A list of validation functions for the field (see [Django Validators](https://docs.djangoproject.com/en/stable/ref/validators/)).
  * **form_classname** – A value to add to the form field’s `class` attribute when rendered on the page editing form.
  * **form_attrs** – A dictionary of additional attributes to add to the form field’s wrapper element when rendered on the page editing form.

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

Bases: [`FieldBlock`](#wagtail.blocks.FieldBlock)

A single-line text input that validates that the string is a valid URL. The following keyword arguments are accepted in addition to the standard ones:

* **Parameters:**
  * **required** – If true (the default), the field cannot be left blank.
  * **max_length** – The maximum allowed length of the field.
  * **min_length** – The minimum allowed length of the field.
  * **help_text** – Help text to display alongside the field.
  * **validators** – A list of validation functions for the field (see [Django Validators](https://docs.djangoproject.com/en/stable/ref/validators/)).
  * **form_classname** – A value to add to the form field’s `class` attribute when rendered on the page editing form.
  * **form_attrs** – A dictionary of additional attributes to add to the form field’s wrapper element when rendered on the page editing form.

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

Bases: [`FieldBlock`](#wagtail.blocks.FieldBlock)

A checkbox. The following keyword arguments are accepted in addition to the standard ones:

* **Parameters:**
  * **required** – If true (the default), the checkbox must be ticked to proceed. As with Django’s `BooleanField`, a checkbox that can be left ticked or unticked must be explicitly denoted with `required=False`.
  * **help_text** – Help text to display alongside the field.
  * **form_classname** – A value to add to the form field’s `class` attribute when rendered on the page editing form.
  * **form_attrs** – A dictionary of additional attributes to add to the form field’s wrapper element when rendered on the page editing form.

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

Bases: [`FieldBlock`](#wagtail.blocks.FieldBlock)

A date picker. The following keyword arguments are accepted in addition to the standard ones:

* **Parameters:**
  * **format** – Date format. This must be one of the recognized formats listed in the [`DATE_INPUT_FORMATS`](https://docs.djangoproject.com/en/stable/ref/settings/#std-setting-DATE_INPUT_FORMATS) setting. If not specified Wagtail will use the `WAGTAIL_DATE_FORMAT` setting with fallback to `"%Y-%m-%d"`.
  * **required** – If true (the default), the field cannot be left blank.
  * **help_text** – Help text to display alongside the field.
  * **validators** – A list of validation functions for the field (see [Django Validators](https://docs.djangoproject.com/en/stable/ref/validators/)).
  * **form_classname** – A value to add to the form field’s `class` attribute when rendered on the page editing form.
  * **form_attrs** – A dictionary of additional attributes to add to the form field’s wrapper element when rendered on the page editing form.

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

Bases: [`FieldBlock`](#wagtail.blocks.FieldBlock)

A time picker. The following keyword arguments are accepted in addition to the standard ones:

* **Parameters:**
  * **format** – Time format. This must be one of the recognized formats listed in the [`TIME_INPUT_FORMATS`](https://docs.djangoproject.com/en/stable/ref/settings/#std-setting-TIME_INPUT_FORMATS) setting. If not specified Wagtail will use the `WAGTAIL_TIME_FORMAT` setting with fallback to `"%H:%M"`.
  * **required** – If true (the default), the field cannot be left blank.
  * **help_text** – Help text to display alongside the field.
  * **validators** – A list of validation functions for the field (see [Django Validators](https://docs.djangoproject.com/en/stable/ref/validators/)).
  * **form_classname** – A value to add to the form field’s `class` attribute when rendered on the page editing form.
  * **form_attrs** – A dictionary of additional attributes to add to the form field’s wrapper element when rendered on the page editing form.

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

Bases: [`FieldBlock`](#wagtail.blocks.FieldBlock)

A combined date/time picker. The following keyword arguments are accepted in addition to the standard ones:

* **Parameters:**
  * **format** – Date/time format. This must be one of the recognized formats listed in the [`DATETIME_INPUT_FORMATS`](https://docs.djangoproject.com/en/stable/ref/settings/#std-setting-DATETIME_INPUT_FORMATS) setting. If not specified Wagtail will use the `WAGTAIL_DATETIME_FORMAT` setting with fallback to `"%Y-%m-%d %H:%M"`.
  * **required** – If true (the default), the field cannot be left blank.
  * **help_text** – Help text to display alongside the field.
  * **validators** – A list of validation functions for the field (see [Django Validators](https://docs.djangoproject.com/en/stable/ref/validators/)).
  * **form_classname** – A value to add to the form field’s `class` attribute when rendered on the page editing form.
  * **form_attrs** – A dictionary of additional attributes to add to the form field’s wrapper element when rendered on the page editing form.

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

Bases: [`FieldBlock`](#wagtail.blocks.FieldBlock)

A WYSIWYG editor for creating formatted text including links, bold / italics etc. The following keyword arguments are accepted in addition to the standard ones:

* **Parameters:**
  * **editor** – The rich text editor to be used (see [WAGTAILADMIN_RICH_TEXT_EDITORS](../settings.md#wagtailadmin-rich-text-editors)).
  * **features** – Specifies the set of features allowed (see [Limiting features in a rich text field](../../advanced_topics/customization/page_editing_interface.md#rich-text-features)).
  * **required** – If true (the default), the field cannot be left blank.
  * **max_length** – The maximum allowed length of the field. Only text is counted; rich text formatting, embedded content and paragraph / line breaks do not count towards the limit.
  * **min_length** – The minimum allowed length of the field. Only text is counted; rich text formatting, embedded content and paragraph / line breaks do not count towards the limit.
  * **search_index** – If false (default true), the content of this block will not be indexed for searching.
  * **help_text** – Help text to display alongside the field.
  * **validators** – A list of validation functions for the field (see [Django Validators](https://docs.djangoproject.com/en/stable/ref/validators/)).
  * **form_classname** – A value to add to the form field’s `class` attribute when rendered on the page editing form.
  * **form_attrs** – A dictionary of additional attributes to add to the form field’s wrapper element when rendered on the page editing form.

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

Bases: [`FieldBlock`](#wagtail.blocks.FieldBlock)

A text area for entering raw HTML which will be rendered unescaped in the page output. The following keyword arguments are accepted in addition to the standard ones:

* **Parameters:**
  * **required** – If true (the default), the field cannot be left blank.
  * **max_length** – The maximum allowed length of the field.
  * **min_length** – The minimum allowed length of the field.
  * **help_text** – Help text to display alongside the field.
  * **validators** – A list of validation functions for the field (see [Django Validators](https://docs.djangoproject.com/en/stable/ref/validators/)).
  * **form_classname** – A value to add to the form field’s `class` attribute when rendered on the page editing form.
  * **form_attrs** – A dictionary of additional attributes to add to the form field’s wrapper element when rendered on the page editing form.

#### WARNING
When this block is in use, there is nothing to prevent editors from inserting malicious scripts into the page, including scripts that would allow the editor to acquire administrator privileges when another administrator views the page. Do not use this block unless your editors are fully trusted.

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

Bases: [`TextBlock`](#wagtail.blocks.TextBlock)

A text field, the contents of which will be wrapped in an HTML <blockquote> tag pair in the page output. The following keyword arguments are accepted in addition to the standard ones:

* **Parameters:**
  * **required** – If true (the default), the field cannot be left blank.
  * **max_length** – The maximum allowed length of the field.
  * **min_length** – The minimum allowed length of the field.
  * **help_text** – Help text to display alongside the field.
  * **validators** – A list of validation functions for the field (see [Django Validators](https://docs.djangoproject.com/en/stable/ref/validators/)).
  * **form_classname** – A value to add to the form field’s `class` attribute when rendered on the page editing form.
  * **form_attrs** – A dictionary of additional attributes to add to the form field’s wrapper element when rendered on the page editing form.

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

Bases: `BaseChoiceBlock`

A dropdown select box for choosing one item from a list of choices. The following keyword arguments are accepted in addition to the standard ones:

* **Parameters:**
  * **choices** – A list of choices, in any format accepted by Django’s [`choices`](https://docs.djangoproject.com/en/stable/ref/models/fields/#django.db.models.Field.choices) parameter for model fields, or a callable returning such a list.
  * **required** – If true (the default), the field cannot be left blank.
  * **help_text** – Help text to display alongside the field.
  * **search_index** – If false (default true), the content of this block will not be indexed for searching.
  * **widget** – The form widget to render the field with (see [Django Widgets](https://docs.djangoproject.com/en/stable/ref/forms/widgets/)).
  * **validators** – A list of validation functions for the field (see [Django Validators](https://docs.djangoproject.com/en/stable/ref/validators/)).
  * **form_classname** – A value to add to the form field’s `class` attribute when rendered on the page editing form.
  * **form_attrs** – A dictionary of additional attributes to add to the form field’s wrapper element when rendered on the page editing form.

`ChoiceBlock` can also be subclassed to produce a reusable block with the same list of choices everywhere it is used. For example, a block definition such as:

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

Could be rewritten as a subclass of ChoiceBlock:

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

    class Meta:
        icon = 'cup'
```

`StreamField` definitions can then refer to `DrinksChoiceBlock()` in place of the full `ChoiceBlock` definition. Note that this only works when `choices` is a fixed list, not a callable.

<a id="streamfield-multiplechoiceblock"></a>

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

Bases: `BaseChoiceBlock`

A select box for choosing multiple items from a list of choices. The following keyword arguments are accepted in addition to the standard ones:

* **Parameters:**
  * **choices** – A list of choices, in any format accepted by Django’s [`choices`](https://docs.djangoproject.com/en/stable/ref/models/fields/#django.db.models.Field.choices) parameter for model fields, or a callable returning such a list.
  * **required** – If true (the default), the field cannot be left blank.
  * **help_text** – Help text to display alongside the field.
  * **search_index** – If false (default true), the content of this block will not be indexed for searching.
  * **widget** – The form widget to render the field with (see [Django Widgets](https://docs.djangoproject.com/en/stable/ref/forms/widgets/)).
  * **validators** – A list of validation functions for the field (see [Django Validators](https://docs.djangoproject.com/en/stable/ref/validators/)).
  * **form_classname** – A value to add to the form field’s `class` attribute when rendered on the page editing form.
  * **form_attrs** – A dictionary of additional attributes to add to the form field’s wrapper element when rendered on the page editing form.

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

Bases: `ChooserBlock`

A control for selecting a page object, using Wagtail’s page browser. The following keyword arguments are accepted in addition to the standard ones:

* **Parameters:**
  * **required** – If true (the default), the field cannot be left blank.
  * **page_type** – Restrict choices to one or more specific page types; by default, any page type may be selected. Can be specified as a page model class, model name (as a string), or a list or tuple of these.
  * **can_choose_root** – Defaults to false. If true, the editor can choose the tree root as a page. Normally this would be undesirable since the tree root is never a usable page, but in some specialized cases, it may be appropriate. For example, a block providing a feed of related articles could use a PageChooserBlock to select which subsection of the site articles will be taken from, with the root corresponding to ‘everywhere’.

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

Bases: `BaseDocumentChooserBlock`

A control to allow the editor to select an existing document object, or upload a new one. The following additional keyword argument is accepted:

* **Parameters:**
  **required** – If true (the default), the field cannot be left blank.

<a id="streamfield-imageblock"></a>

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

Bases: [`StructBlock`](#wagtail.blocks.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.

An accessibility-focused control to allow the editor to select an existing image, or upload a new one. This has provision for adding alt text and indicating whether images are purely decorative, and is the Wagtail-recommended approach to uploading images. The following additional keyword argument is accepted:

* **Parameters:**
  **required** – If true (the default), the field cannot be left blank.

`ImageBlock` incorporates backwards compatibility with `ImageChooserBlock`. A block initially defined as `ImageChooserBlock` can be directly replaced with `ImageBlock` - existing data created with `ImageChooserBlock` will be handled automatically and changed to `ImageBlock`’s data format when the field is resaved.

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

Bases: `ChooserBlock`

A control to allow the editor to select an existing image, or upload a new one. The following additional keyword argument is accepted:

* **Parameters:**
  **required** – If true (the default), the field cannot be left blank.

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

Bases: `ChooserBlock`

A control to allow the editor to select a snippet object. Requires one positional argument: the snippet class to choose from. The following additional keyword argument is accepted:

* **Parameters:**
  **required** – If true (the default), the field cannot be left blank.

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

Bases: [`URLBlock`](#wagtail.blocks.URLBlock)

A field for the editor to enter a URL to a media item (such as a YouTube video) to appear as embedded media on the page. The following keyword arguments are accepted in addition to the standard ones:

* **Parameters:**
  * **required** – If true (the default), the field cannot be left blank.
  * **max_width** – The maximum width of the embed, in pixels; this will be passed to the provider when requesting the embed.
  * **max_height** – The maximum height of the embed, in pixels; this will be passed to the provider when requesting the embed.:param max_length: The maximum allowed length of the field.
  * **min_length** – The minimum allowed length of the field.
  * **help_text** – Help text to display alongside the field.

<a id="streamfield-staticblock"></a>

## Structural block types

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

Bases: [`Block`](#wagtail.blocks.Block)

A block that just ‘exists’ and has no fields.

A block which doesn’t have any fields, thus passes no particular values to its template during rendering. This can be useful if you need the editor to be able to insert some content that is always the same or doesn’t need to be configured within the page editor, such as an address, embed code from third-party services, or more complex pieces of code if the template uses template tags. The following additional keyword argument is accepted:

* **Parameters:**
  **admin_text** – A text string to display in the admin when this block is used. By default, some default text (which contains the `label` keyword argument if you pass it) will be displayed in the editor interface, so that the block doesn’t look empty, but this can be customized by passing `admin_text`:

```python
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` can also be subclassed to produce a reusable block with the same configuration everywhere it is used:

```python
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)

Bases: `BaseStructBlock`

A block consisting of a fixed group of sub-blocks to be displayed together. Takes a list of `(name, block_definition)` tuples as its first argument:

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

Alternatively, StructBlock can be subclassed to specify a reusable set of sub-blocks:

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

    class Meta:
        icon = 'user'
```

The `Meta` class supports the properties `default`, `label`, `icon` and `template`, which have the same meanings as when they are passed to the block’s constructor.

This defines `PersonBlock()` as a block type for use in StreamField definitions:

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

The following additional options are available as either keyword arguments or Meta class attributes:

* **Parameters:**
  * **form_classname** – An HTML `class` attribute to set on the root element of this block as displayed in the editing interface, defaults to `struct-block`. When overriding, you may need to include the default `struct-block` class if you have custom code or use a third-party package that relies on it. See [Adding custom classes and attributes](../../advanced_topics/customization/streamfield_blocks.md#structblock-custom-classes-and-attributes).
  * **form_attrs** – A dictionary of additional attributes to set on the root element of this block as displayed in the editing interface. See [Adding custom classes and attributes](../../advanced_topics/customization/streamfield_blocks.md#structblock-custom-classes-and-attributes).
  * **form_template** – Path to a Django template to use to render this block’s form. See [Customizing the template of StructBlock forms](../../advanced_topics/customization/streamfield_blocks.md#structblock-custom-template).
  * **collapsed** – When true and the block is within another `StructBlock`, the block is initially collapsed. This can be useful for blocks with many sub-blocks, or blocks that are not expected to be edited frequently. See [Customizing the initial collapsible state](../../advanced_topics/customization/streamfield_blocks.md#structblock-initial-collapsible).
  * **value_class** – A subclass of `wagtail.blocks.StructValue` to use as the type of returned values for this block. See [Additional methods and properties on StructBlock values](../../advanced_topics/customization/streamfield_blocks.md#custom-value-class-for-structblock).
  * **search_index** – If false (default true), the content of this block will not be indexed for searching.
  * **label_format** – Determines the summary label shown after the `label` when the block is collapsed in the editing interface. By default, the value of the first sub-block in the StructBlock 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 `""`.
  * **form_layout** – A list of block names or `BlockGroup` instances to determine the order in which sub-blocks are displayed in the editing interface. Alternatively, a `BlockGroup` instance can be provided instead of a list, to define a group of `children` and `settings` blocks. See [Changing the order and grouping of child blocks](../../advanced_topics/customization/streamfield_blocks.md#structblock-custom-order-and-grouping) and [`BlockGroup`](#wagtail.blocks.BlockGroup) for more details.

#### get_form_layout() → [BlockGroup](#wagtail.blocks.BlockGroup)

Return the [`BlockGroup`](#wagtail.blocks.BlockGroup) representing the form layout for this
`StructBlock`.

#### Versionadded
Added in version 7.3: The `form_layout` option and the `get_form_layout` method were added.

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

Bases: [`Block`](#wagtail.blocks.Block)

A block consisting of many sub-blocks, all of the same type. The editor can add an unlimited number of sub-blocks, and re-order and delete them. Takes the definition of the sub-block as its first argument:

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

Any block type is valid as the sub-block type, including structural types:

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

The following additional options are available as either keyword arguments or Meta class attributes:

* **Parameters:**
  * **form_classname** – An HTML `class` attribute to set on the root element of this block as displayed in the editing interface.
  * **form_attrs** – A dictionary of additional attributes to set on the root element of this block as displayed in the editing interface.
  * **min_num** – Minimum number of sub-blocks that the list must have.
  * **max_num** – Maximum number of sub-blocks that the list may have.
  * **search_index** – If false (default true), the content of this block will not be indexed for searching.
  * **collapsed** – When true, all sub-blocks are initially collapsed.

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

Bases: `BaseStreamBlock`

A block consisting of a sequence of sub-blocks of different types, which can be mixed and reordered at will. Used as the overall mechanism of the StreamField itself, but can also be nested or used within other structural block types. Takes a list of `(name, block_definition)` tuples as its first argument:

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

As with StructBlock, the list of sub-blocks can also be provided as a subclass of StreamBlock:

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

    class Meta:
        icon='cogs'
```

Since `StreamField` accepts an instance of `StreamBlock` as a parameter, in place of a list of block types, this makes it possible to re-use a common set of block types without repeating definitions:

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

`StreamBlock` accepts the following additional options as either keyword arguments or `Meta` properties:

* **Parameters:**
  * **required** – If true (the default), at least one sub-block must be supplied. This is ignored when using the `StreamBlock` as the top-level block of a StreamField; in this case, the StreamField’s `blank` property is respected instead.
  * **min_num** – Minimum number of sub-blocks that the stream must have.
  * **max_num** – Maximum number of sub-blocks that the stream may have.
  * **search_index** – If false (default true), the content of this block will not be indexed for searching.
  * **block_counts** – Specifies the minimum and maximum number of each block type, as a dictionary mapping block names to dicts with (optional) `min_num` and `max_num` fields.
  * **collapsed** – When true, all sub-blocks are initially collapsed.
  * **form_classname** – An HTML `class` attribute to set on the root element of this block as displayed in the editing interface.
  * **form_attrs** – A dictionary of additional attributes to set on the root element of this block as displayed in the editing interface.

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

```python
class EventPromotionsBlock(blocks.StreamBlock):
    hashtag = blocks.CharBlock()
    post_date = blocks.DateBlock()

    class Meta:
        form_classname = 'event-promotions'
```

## Supporting components

### `BlockGroup`

#### Versionadded
Added in version 7.3: The `BlockGroup` class was added.

### *class* wagtail.blocks.BlockGroup(children: [list](https://docs.python.org/3/library/stdtypes.html#list)[[str](https://docs.python.org/3/library/stdtypes.html#str) | [BlockGroup](#wagtail.blocks.BlockGroup)], settings: [list](https://docs.python.org/3/library/stdtypes.html#list)[[str](https://docs.python.org/3/library/stdtypes.html#str) | [BlockGroup](#wagtail.blocks.BlockGroup)] = None, heading='', classname='', help_text='', icon='placeholder', attrs: [dict](https://docs.python.org/3/library/stdtypes.html#dict) | [None](https://docs.python.org/3/library/constants.html#None) = None, label_format: [str](https://docs.python.org/3/library/stdtypes.html#str) | [None](https://docs.python.org/3/library/constants.html#None) = None)

A grouping of blocks within a [`StructBlock`](#wagtail.blocks.StructBlock)’s form layout in the
editing interface. Can be used directly as the `form_layout` in
[`StructBlock`](#wagtail.blocks.StructBlock).Meta, or nested within another `BlockGroup`.

* **Parameters:**
  * **children** ([*list*](https://docs.python.org/3/library/stdtypes.html#list) *[*[*str*](https://docs.python.org/3/library/stdtypes.html#str) *|* [*BlockGroup*](#wagtail.blocks.BlockGroup) *]*) – A list of block names or nested `BlockGroup` that will be
    rendered in the main content area.
  * **settings** ([*list*](https://docs.python.org/3/library/stdtypes.html#list) *[*[*str*](https://docs.python.org/3/library/stdtypes.html#str) *|* [*BlockGroup*](#wagtail.blocks.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`](#wagtail.blocks.StructBlock), these attributes are ignored in
favor of the corresponding attributes on `StructBlock.Meta`.

* **Parameters:**
  * **heading** ([*str*](https://docs.python.org/3/library/stdtypes.html#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*](https://docs.python.org/3/library/stdtypes.html#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*](https://docs.python.org/3/library/stdtypes.html#str)) – Help text to display below the block group’s heading.
  * **icon** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – The name of the icon to display alongside the block group’s heading.
  * **attrs** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)) – A dictionary of HTML attributes to add to the block group’s main content area.
  * **label_format** ([*str*](https://docs.python.org/3/library/stdtypes.html#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 `""`.

#### Methods

#### 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.
