使用 FOR 循环生成 Wagtail 字段
Generate Wagtail Field's using a FOR loop
我是 Wagtail 的新手,想通过遍历这样的名称列表在我的 models.py 中创建多个字段...
class HomePage(Page):
myFields = [ ('paragraph', blocks.RichTextBlock(classname="oneA")),('image', ImageChooserBlock()) ]
mySections = ['sectionOne', 'sectionTwo', 'sectionThree']
for mySection in mySections:
mySection = StreamField(myFields,null=True,blank=True)
content_panels = Page.content_panels + [
StreamFieldPanel('sectionOne'), StreamFieldPanel('sectionTwo'), StreamFieldPanel('sectionThree'),
]
这会产生一条错误消息...
django.core.exceptions.FieldDoesNotExist: HomePage has no field named 'sectionOne'
有没有办法做到这一点,或者我必须像这样单独声明每个:
sectionOne = StreamField(myFields,null=True,blank=True)
这不起作用,因为 mySection = StreamField(...)
只是重复定义一个名为 mySection
的字段 - Python 无法知道您想要定义一个名称为当前给出 in mySection
.
我认为实现此目的的唯一方法是在元类中设置字段,这几乎肯定会比仅重复该行更复杂且可读性更差。参见 , Dynamically create class attributes
我是 Wagtail 的新手,想通过遍历这样的名称列表在我的 models.py 中创建多个字段...
class HomePage(Page):
myFields = [ ('paragraph', blocks.RichTextBlock(classname="oneA")),('image', ImageChooserBlock()) ]
mySections = ['sectionOne', 'sectionTwo', 'sectionThree']
for mySection in mySections:
mySection = StreamField(myFields,null=True,blank=True)
content_panels = Page.content_panels + [
StreamFieldPanel('sectionOne'), StreamFieldPanel('sectionTwo'), StreamFieldPanel('sectionThree'),
]
这会产生一条错误消息...
django.core.exceptions.FieldDoesNotExist: HomePage has no field named 'sectionOne'
有没有办法做到这一点,或者我必须像这样单独声明每个:
sectionOne = StreamField(myFields,null=True,blank=True)
这不起作用,因为 mySection = StreamField(...)
只是重复定义一个名为 mySection
的字段 - Python 无法知道您想要定义一个名称为当前给出 in mySection
.
我认为实现此目的的唯一方法是在元类中设置字段,这几乎肯定会比仅重复该行更复杂且可读性更差。参见