Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

python - Looping through wagtail contents

I’m using wagtail to manage content in my Django app. In my model, I used a structured block like so:

# prefered 
class SectionBlock(blocks.StructBlock):
    header = blocks.CharBlock()
    content = blocks.RichTextBlock()

My page is expected to have multiple distinct headers like introduction, conclusion, etc however the template iteration keeps looping through the first header (introduction). The question is do I rename each item in my SectionBlock class so I can directly access it in the template or there is a simpler solution?

class SectionBlock(blocks.StructBlock):
    header1 = blocks.CharBlock()
    content1 = blocks.RichTextBlock()
    header2 = blocks.CharBlock()
    content2 = blocks.RichTextBlock()
{% for block in blocks %}
{{ block.value.header1 }}
{{ block.value.header2 }}
{% endfor %}
question from:https://stackoverflow.com/questions/65640950/looping-through-wagtail-contents

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The custom SectionBlock can be used with a StreamField, allowing the editors to add as many sections as needed.

models.py

class SectionBlock(blocks.StructBlock):
    header = blocks.CharBlock()
    content = blocks.RichTextBlock()


class ExamplePage(Page):
    body = StreamField(
        [
            ('section', SectionBlock())
        ], blank=True
    )

template.html

{% for section in page.body %}
   {{ section.value.header }}
   {{ section.value.content }}
{% endfor %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...