0

我想要的是

我将通过 wegtail 构建一个 Web 应用程序,例如新闻分发应用程序。我在 Blocks.py 上创建了类,继承到 models.py 并在 html 上编码以显示它们。这个类意味着输入文章信息,如标题和url,并列出它们。尽管我对 html 进行了编码并且它被识别了,但是它并没有显示出来。

错误信息

我没有收到一些错误消息。请看这张照片,我编码了 {{ self }} 并显示出来。 我们可以看到文章标题和更多信息。

详细地

项目树

这是我的项目的构成。 项目树

编码

#streams/blocks.py
#python file

#block model to input article info
class ArticleIndexBlock(blocks.StructBlock):
    articles = blocks.ListBlock(
        blocks.StructBlock(
            [
                ("article_image", ImageChooserBlock(required=True)),
                ("article_title", blocks.CharBlock(required=True, max_length=40)),
                ("article_text", blocks.TextBlock(required=True, max_length=200)),
                ("article_url", blocks.URLBlock(required=False)),
            ]
        )
    )

    class Meta:
        template = "streams/article_index_block.html"
        icon = "edit"
        label = "Article"
#articles/models.py
#python file

#models inherited from Streams/blocks.py
class ArticleIndexPage(Page):
    template = "articles/article_index.html"

    content = StreamField(
        [
            ("article_index_block", blocks.ArticleIndexBlock()),
        ],
        null=True,
        blank=True,
    )

    content_panels = Page.content_panels + [
        StreamFieldPanel("content"),
    ]

    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        context["posts"] = ArticleIndexPage.objects.live().public()
        return context

    class Meta:
        verbose_name = "Article index Page"
        verbose_name_plural = "Article index Pages"

<!--article_index.html-->

{% extends 'base.html' %}
{% load wagtailcore_tags %}

{% block content %}
    <h1>{{ self.title }}</h1>


    {% for block in page.content %}
        {% include_block block%}
    {% endfor %}

{% endblock content %}

<!--article_index_block.html-->

<div class="container">
  <h3>{{ self.article_title }}</h3>

</div>

</hr>
4

1 回答 1

1

ArticleIndexBlock没有article_title财产。正如当前定义的那样,它有一个属性 ,articles它是一个 StructBlocks 的列表,具有各种属性,包括article_title

很可能,您不需要所有这些嵌套块 - StreamField 已经是块列表,因此您不需要在块内定义列表。只需直接在类上定义您的字段:

class ArticleIndexBlock(blocks.StructBlock):
    article_image = ImageChooserBlock(required=True)
    article_title = blocks.CharBlock(required=True, max_length=40)
    article_text = blocks.TextBlock(required=True, max_length=200)
    article_url = blocks.URLBlock(required=False)

    class Meta:
        template = "streams/article_index_block.html"
        icon = "edit"
        label = "Article"

然后你的模板就可以工作了。

但是,如果您确实希望您的“文章”块包含文章列表(因此整个页面是列表列表),您需要在 article_index_block.html 中循环它们。

<div class="container">
    {% for article in self.articles %}
        <h3>{{ article.article_title }}</h3>
    {% endfor %}
</div>
于 2020-08-07T08:13:03.910 回答