InlinePanel 中引用对象的 Wagtail 渲染

Wagtail rendering of referenced objects in an InlinePanel

在我的文章页面模型中,我有一个 InlinePanel('technologies', label="Technologies"),,它加载了一个 ArticlesPageTechnologies(Orderable),它正在使用 PageChooserPanel('technologies', 'rb_tech_portfolio.TechnologiesPage'),

一切正常。但我想做的是列出这些引用页面的链接,但我似乎无法找出最好的方法来做到这一点。我得到的最接近的是 {% for technology in page.technologies.all %} 但这只是给了我连接 2 个页面模型的对象,而我想要引用的对象。这一切都准备好使用了吗,还是我需要在 def_context 中做一个额外的查询才能做到这一点?

谢谢, 旦


技术内联面板

class ArticlesPageTechnologies(Orderable):
    page = ParentalKey(ArticlesPage, on_delete=models.CASCADE, related_name='technologies')

    technologies = models.ForeignKey(
        'wagtailcore.Page',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+',
    )

    panels = [
        PageChooserPanel('technologies', 'rb_tech_portfolio.TechnologiesPage'),
    ]

文章的页面模型

class ArticlesPage(Page):
    body = RichTextField(blank=True)
    thumbnail = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+'
    )

    content_panels = Page.content_panels + [
        FieldPanel('body', classname="full"),
        ImageChooserPanel('thumbnail'),
        InlinePanel('technologies', label="Technologies"),
    ]

    def get_context(self, request, *args, **kwargs):
        """Adding custom stuff to our context."""
        context = super().get_context(request, *args, **kwargs)
        # Get all posts
        posts = ArticlesPage.objects.live().public().order_by('-date')[:5]

        context["posts"] = posts
        return context

文章页面模板

{% extends "base.html" %}

{% block body_class %}template-article{% endblock %}

{% block content %}
{% comment %}
{% for post in posts %}
{{ post.url }}
{% endfor %}
{% endcomment %}

<div class="row">
  <div class="col-9 col-12-medium">
    <section>
      <header>
        <h1>{{ page.title }}</h1>
      </header>
      {{ page.body|safe }}
    </section>
    </ul>
  </div>
  <div class="col-3 col-12-medium">

    <!-- Sidebar -->
    <section>

      <header>
        <h2>Technologies</h2>
      </header>

      <ul class="link-list">
        {% for technology in page.technologies.all %}
          <li>{{ technology.select_related.title }}</li>
        {% endfor %}
      </ul>

    </section>

  </div>
</div>

{% endblock content %}

这应该有效:

 {% for technology in page.technologies.all %}
     <li>{{ technology.technologies.title }}</li>
 {% endfor %}

如果这看起来有点混乱,那是因为您的 ArticlesPageTechnologies 模型使用 technologies 的方式有点混乱。每个 ArticlesPageTechnologies 对象将一个 单一 技术链接到您的页面,而不是多个 - 多样性是通过在您的 InlinePanel 中拥有多个这样的对象来实现的。

我建议您将 tehnologies 外键重命名为 technology 以反映这一事实。如果你这样做那么你的模板逻辑(功能上与上面相同,但希望变量名称更容易理解)将是:

 {% for page_technology in page.technologies.all %}
     <li>{{ page_technology.technology.title }}</li>
 {% endfor %}