(streamfield_topic)= # How to use StreamField for mixed content StreamField provides a content editing model suitable for pages that do not follow a fixed structure -- such as blog posts or news stories -- where the text may be interspersed with subheadings, images, pull quotes and video. It's also suitable for more specialised content types, such as maps and charts (or, for a programming blog, code snippets). In this model, these different content types are represented as a sequence of 'blocks', which can be repeated and arranged in any order. For further background on StreamField, and why you would use it instead of a rich text field for the article body, see the blog post [Rich text fields and faster horses](https://torchbox.com/blog/rich-text-fields-and-faster-horses/). StreamField also offers a rich API to define your own block types, ranging from simple collections of sub-blocks (such as a 'person' block consisting of first name, surname and photograph) to completely custom components with their own editing interface. Within the database, the StreamField content is stored as JSON, ensuring that the full informational content of the field is preserved, rather than just an HTML representation of it. ## Using StreamField `StreamField` is a model field that can be defined within your page model like any other field: ```python from django.db import models from wagtail.models import Page from wagtail.fields import StreamField from wagtail import blocks from wagtail.admin.panels import FieldPanel from wagtail.images.blocks import ImageChooserBlock class BlogPage(Page): author = models.CharField(max_length=255) date = models.DateField("Post date") body = StreamField([ ('heading', blocks.CharBlock(form_classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ], use_json_field=True) content_panels = Page.content_panels + [ FieldPanel('author'), FieldPanel('date'), FieldPanel('body'), ] ``` In this example, the body field of `BlogPage` is defined as a `StreamField` where authors can compose content from three different block types: headings, paragraphs, and images, which can be used and repeated in any order. The block types available to authors are defined as a list of `(name, block_type)` tuples: 'name' is used to identify the block type within templates, and should follow the standard Python conventions for variable names: lower-case and underscores, no spaces. You can find the complete list of available block types in the [](streamfield_block_reference). ```{note} StreamField is not a direct replacement for other field types such as RichTextField. If you need to migrate an existing field to StreamField, refer to [](streamfield_migrating_richtext). ``` ```{versionchanged} 3.0 The `use_json_field=True` argument was added. This indicates that the database's native JSONField support should be used for this field, and is a temporary measure to assist in migrating StreamFields created on earlier Wagtail versions; it will become the default in a future release. ``` (streamfield_template_rendering)= ## Template rendering StreamField provides an HTML representation for the stream content as a whole, as well as for each individual block. To include this HTML into your page, use the `{% include_block %}` tag: ```html+django {% load wagtailcore_tags %} ... {% include_block page.body %} ``` In the default rendering, each block of the stream is wrapped in a `
` element (where `my_block_name` is the block name given in the StreamField definition). If you wish to provide your own HTML markup, you can instead iterate over the field's value, and invoke `{% include_block %}` on each block in turn: ```html+django {% load wagtailcore_tags %} ...
{% for block in page.body %}
{% include_block block %}
{% endfor %}
``` For more control over the rendering of specific block types, each block object provides `block_type` and `value` properties: ```html+django {% load wagtailcore_tags %} ...
{% for block in page.body %} {% if block.block_type == 'heading' %}

{{ block.value }}

{% else %}
{% include_block block %}
{% endif %} {% endfor %}
``` ## Combining blocks In addition to using the built-in block types directly within StreamField, it's possible to construct new block types by combining sub-blocks in various ways. Examples of this could include: - An "image with caption" block consisting of an image chooser and a text field - A "related links" section, where an author can provide any number of links to other pages - A slideshow block, where each slide may be an image, text or video, arranged in any order Once a new block type has been built up in this way, you can use it anywhere where a built-in block type would be used - including using it as a component for yet another block type. For example, you could define an image gallery block where each item is an "image with caption" block. ### StructBlock `StructBlock` allows you to group several 'child' blocks together to be presented as a single block. The child blocks are passed to `StructBlock` as a list of `(name, block_type)` tuples: ```{code-block} python :emphasize-lines: 2-7 body = StreamField([ ('person', blocks.StructBlock([ ('first_name', blocks.CharBlock()), ('surname', blocks.CharBlock()), ('photo', ImageChooserBlock(required=False)), ('biography', blocks.RichTextBlock()), ])), ('heading', blocks.CharBlock(form_classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ], use_json_field=True) ``` When reading back the content of a StreamField (such as when rendering a template), the value of a StructBlock is a dict-like object with keys corresponding to the block names given in the definition: ```html+django
{% for block in page.body %} {% if block.block_type == 'person' %}
{% image block.value.photo width-400 %}

{{ block.value.first_name }} {{ block.value.surname }}

{{ block.value.biography }}
{% else %} (rendering for other block types) {% endif %} {% endfor %}
``` ### Subclassing `StructBlock` Placing a StructBlock's list of child blocks inside a `StreamField` definition can often be hard to read, and makes it difficult for the same block to be reused in multiple places. As an alternative, `StructBlock` can be subclassed, with the child blocks defined as attributes on the subclass. The 'person' block in the above example could be rewritten as: ```python class PersonBlock(blocks.StructBlock): first_name = blocks.CharBlock() surname = blocks.CharBlock() photo = ImageChooserBlock(required=False) biography = blocks.RichTextBlock() ``` `PersonBlock` can then be used in a `StreamField` definition in the same way as the built-in block types: ```python body = StreamField([ ('person', PersonBlock()), ('heading', blocks.CharBlock(form_classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ], use_json_field=True) ``` ### Block icons In the menu that content authors use to add new blocks to a StreamField, each block type has an associated icon. For StructBlock and other structural block types, a placeholder icon is used, since the purpose of these blocks is specific to your project. To set a custom icon, pass the option `icon` as either a keyword argument to `StructBlock`, or an attribute on a `Meta` class: ```{code-block} python :emphasize-lines: 7 body = StreamField([ ('person', blocks.StructBlock([ ('first_name', blocks.CharBlock()), ('surname', blocks.CharBlock()), ('photo', ImageChooserBlock(required=False)), ('biography', blocks.RichTextBlock()), ], icon='user')), ('heading', blocks.CharBlock(form_classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ], use_json_field=True) ``` ```{code-block} python :emphasize-lines: 7-8 class PersonBlock(blocks.StructBlock): first_name = blocks.CharBlock() surname = blocks.CharBlock() photo = ImageChooserBlock(required=False) biography = blocks.RichTextBlock() class Meta: icon = 'user' ``` For a list of the recognised icon identifiers, see the [](styleguide). ### ListBlock `ListBlock` defines a repeating block, allowing content authors to insert as many instances of a particular block type as they like. For example, a 'gallery' block consisting of multiple images can be defined as follows: ```{code-block} python :emphasize-lines: 2 body = StreamField([ ('gallery', blocks.ListBlock(ImageChooserBlock())), ('heading', blocks.CharBlock(form_classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ], use_json_field=True) ``` When reading back the content of a StreamField (such as when rendering a template), the value of a ListBlock is a list of child values: ```html+django
{% for block in page.body %} {% if block.block_type == 'gallery' %} {% else %} (rendering for other block types) {% endif %} {% endfor %}
``` ### StreamBlock `StreamBlock` defines a set of child block types that can be mixed and repeated in any sequence, via the same mechanism as StreamField itself. For example, a carousel that supports both image and video slides could be defined as follows: ```{code-block} python :emphasize-lines: 2-5 body = StreamField([ ('carousel', blocks.StreamBlock([ ('image', ImageChooserBlock()), ('video', EmbedBlock()), ])), ('heading', blocks.CharBlock(form_classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ], use_json_field=True) ``` `StreamBlock` can also be subclassed in the same way as `StructBlock`, with the child blocks being specified as attributes on the class: ```python class CarouselBlock(blocks.StreamBlock): image = ImageChooserBlock() video = EmbedBlock() class Meta: icon = 'image' ``` A StreamBlock subclass defined in this way can also be passed to a `StreamField` definition, instead of passing a list of block types. This allows setting up a common set of block types to be used on multiple page types: ```python class CommonContentBlock(blocks.StreamBlock): heading = blocks.CharBlock(form_classname="full title") paragraph = blocks.RichTextBlock() image = ImageChooserBlock() class BlogPage(Page): body = StreamField(CommonContentBlock(), use_json_field=True) ``` When reading back the content of a StreamField, the value of a StreamBlock is a sequence of block objects with `block_type` and `value` properties, just like the top-level value of the StreamField itself. ```html+django
{% for block in page.body %} {% if block.block_type == 'carousel' %} {% else %} (rendering for other block types) {% endif %} {% endfor %}
``` ### Limiting block counts By default, a StreamField can contain an unlimited number of blocks. The `min_num` and `max_num` options on `StreamField` or `StreamBlock` allow you to set a minimum or maximum number of blocks: ```python body = StreamField([ ('heading', blocks.CharBlock(form_classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ], min_num=2, max_num=5, use_json_field=True) ``` Or equivalently: ```python class CommonContentBlock(blocks.StreamBlock): heading = blocks.CharBlock(form_classname="full title") paragraph = blocks.RichTextBlock() image = ImageChooserBlock() class Meta: min_num = 2 max_num = 5 ``` The `block_counts` option can be used to set a minimum or maximum count for specific block types. This accepts a dict, mapping block names to a dict containing either or both of `min_num` and `max_num`. For example, to permit between 1 and 3 'heading' blocks: ```python body = StreamField([ ('heading', blocks.CharBlock(form_classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ], block_counts={ 'heading': {'min_num': 1, 'max_num': 3}, }, use_json_field=True) ``` Or equivalently: ```python class CommonContentBlock(blocks.StreamBlock): heading = blocks.CharBlock(form_classname="full title") paragraph = blocks.RichTextBlock() image = ImageChooserBlock() class Meta: block_counts = { 'heading': {'min_num': 1, 'max_num': 3}, } ``` (streamfield_per_block_templates)= ## Per-block templates By default, each block is rendered using simple, minimal HTML markup, or no markup at all. For example, a CharBlock value is rendered as plain text, while a ListBlock outputs its child blocks in a `