Extending Wagtail Streamfields In An Inherited Class
I have a abstract class that have ha StreamField in it. I also have a class CustomPage that inherits from BasePage. I want CustomPage to add a new StructBlock to content. How do i
Solution 1:
The StreamField definition can't be 'extended' directly in this way, but with a bit of re-shuffling you can define a new StreamField that re-uses the same block list:
COMMON_BLOCKS = [
('ad', ...),
('text', ...),
('img', ...),
]
class BasePage(Page):
content = StreamField(COMMON_BLOCKS)
...
class CustomPage(BasePage):
content = StreamField(COMMON_BLOCKS + [
('custom_block', ...),
])
Or using inheritance on StreamBlock (which you might consider a bit neater than concatenating lists:
class CommonStreamBlock(StreamBlock):
ad = ...
text = ...
img = ...
class CustomStreamBlock(CommonStreamBlock):
custom_block = ...
class BasePage(Page):
content = StreamField(CommonStreamBlock())
...
class CustomPage(BasePage):
content = StreamField(CustomStreamBlock())
Also, note that this is only possible since Django 1.10 - older versions of Django don't allow overriding fields of an abstract superclass.
Solution 2:
I found one more solution beside @gasman solutions.
It uses the deconstruct method in Stream field to get all the blocks from BasePage StreamField. It uses those blocks when creating the content StreamField in the CustomPage.
I will use this one for now but i think @gasman last solution is the most beautiful solution.
class BasePage(Page):
content = StreamField([
('ad', ...),
('text', ...),
('img', ...),
])
content_panels = Page.content_panels + [
StreamFieldPanel('content'),
]
@staticmethod
def get_content_blocks():
return list(BasePage.content.field.deconstruct()[2][0])
class Meta:
abstract = True
class CustomPage(BasePage):
content = StreamField(BasePage.get_content_blocks() +
[
('custom_block', ....),
]
)
Post a Comment for "Extending Wagtail Streamfields In An Inherited Class"