wagtail / wagtail-factories

Factory boy classes for wagtail
http://wagtail-factories.readthedocs.io/en/latest/
MIT License
102 stars 41 forks source link

Support nested stream blocks #24

Closed mikemonteith closed 2 years ago

mikemonteith commented 4 years ago

A streamfield can contain stream blocks. A struct block can contain stream blocks.

possible solution here: https://github.com/nhsuk/wagtail-factories/blob/dev/src/wagtail_factories/blocks.py#L158

For blocks:

from wagtail.core import blocks

class MySubStreamBlock(blocks.StreamBlock):
    foo = blocks.CharBlock()
    bar = blocks.CharBlock()

class MyStructBlock(blocks.StructBlock):
    sub_stream = MySubStreamBlock()

class MyStreamBlock(blocks.StreamBlock):
    struct = MyStructBlock()

This requires a factory definition of:

import factory
import wagtail_factories
from . import blocks
from .models import HomePage

class MySubStreamBlockFactory(wagtail_factories.StreamBlockFactory):

    foo = "foo"
    bar = "bar"

    class Meta:
        model = blocks.MySubStreamBlock

class MyStructBlockFactory(wagtail_factories.StructBlockFactory):

    sub_stream = wagtail_factories.StreamBlockSubFactory(MySubStreamBlockFactory)

    class Meta:
        model = blocks.MyStructBlock

class MyStreamBlockFactory(wagtail_factories.StreamBlockFactory):

    struct = factory.SubFactory(MyStructBlockFactory)

    class Meta:
        model = blocks.MyStreamBlock

class HomePageFactory(wagtail_factories.PageFactory):

    content = wagtail_factories.StreamFieldFactory({
        "struct": MyStructBlockFactory,
    }, **{
        "0__struct__sub_stream__0__foo": "foo",
        "0__struct__sub_stream__1__bar": "bar",
        "0__struct__sub_stream__2__foo": "foo2",
    })

    class Meta:
        model = HomePage

I am only using stream blocks as a sub-block of struct blocks in my project, so I haven't tested other combinations of blocks. E.g stream block as a sub-block of a stream-block, stream block inside a list block.

mikemonteith commented 4 years ago

I have opened a work-in-progress PR for this #26

jams2 commented 2 years ago

Thanks @mikemonteith for raising - this is addressed in #55