我有一个抽象类,其中有 ha StreamField 。我还有一个继承自 BasePage 的类 CustomPage。我希望 CustomPage 向内容添加新的 StructBlock。我怎么做?
class BasePage(Page):
content = StreamField([
('ad', ...),
('text', ...),
('img', ...),
])
content_panels = Page.content_panels + [
StreamFieldPanel('content'),
]
class Meta:
abstract = True
class CustomPage(BasePage):
# add ('custom_block', ...) to content streamfield.
StreamField 定义不能直接以这种方式“扩展”,但通过一些重新洗牌,您可以定义一个重新使用相同块列表的新 StreamField:
COMMON_BLOCKS = [
('ad', ...),
('text', ...),
('img', ...),
]
class BasePage(Page):
content = StreamField(COMMON_BLOCKS)
...
class CustomPage(BasePage):
content = StreamField(COMMON_BLOCKS + [
('custom_block', ...),
])
或者在 StreamBlock 上使用继承(您可能认为这比连接列表更简洁:
class CommonStreamBlock(StreamBlock):
ad = ...
text = ...
img = ...
class CustomStreamBlock(CommonStreamBlock):
custom_block = ...
class BasePage(Page):
content = StreamField(CommonStreamBlock())
...
class CustomPage(BasePage):
content = StreamField(CustomStreamBlock())
另外,请注意,这是只能从 Django 1.10 开始 https://docs.djangoproject.com/en/1.10/topics/db/models/#field-name-hiding-is-not-permitted- 旧版本的 Django 不允许覆盖抽象超类的字段。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)