2

I am new to Wagtail and want to create several Field's in my models.py by iterating over a list of names like this ...

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'),
    ]

This produces an error message ...

django.core.exceptions.FieldDoesNotExist: HomePage has no field named 'sectionOne'

Is there a way of doing this, or do I have to declare each one individually like so:

sectionOne = StreamField(myFields,null=True,blank=True)
Inyoka
  • 1,287
  • 16
  • 24
  • 1
    You also might have a look at inline panels. http://docs.wagtail.io/en/v2.0/reference/pages/panels.html#inline-panels – allcaps Oct 05 '18 at 08:07

1 Answers1

2

This doesn't work because mySection = StreamField(...) is just repeatedly defining a field called mySection - there's no way for Python to know that you want to define a field with the name currently given in mySection.

I think the only way to achieve this is to set the fields up in a metaclass, which will almost certainly be more complex and less readable than just repeating the line. See How to dynamically set attributes to a class in models in Django?, Dynamically create class attributes

gasman
  • 23,691
  • 1
  • 38
  • 56