wagtailwagtail-streamfieldwagtail-admin

Default blocks for wagtail's StreamField when a new Page is created


Is there a way to create a page model with a StreamField that has default blocks when a new page is created?

For example I have this custom page:

class CustomPage(Page):
    body = StreamField([("text", TextBlock())])

and I always want to have a text block with a default text inside the body when I open the "add a new page" view.

and how do I do this with a more complex block like ItemList?

class Item(StructBlock):
    text = CharBlock()
    image = ImageChooserBlock()

class ItemList(StructBlock):
    items = StreamBlock([("item", Item()),])

Solution

  • A StreamField field definition accepts a default argument that consists of a list of (block_name, value) tuples. So, for a StreamField whose initial state is a single 'text' block, you could write:

    class CustomPage(Page):
        body = StreamField(
            [("text", TextBlock())],
            default=[("text", "hello world!")]
        )
    

    The same thing should work for more complex block types, but when specifying the block value you'll need to take care to match up the expected value type at every point in the nesting: a StreamBlock corresponds to a list of tuples as above, and a StructBlock corresponds to a dict value, so the default value in your second item would have to be:

    (Or something like that, anyway!)