cru*_*own 8 python django wagtail
在Wagtail CMS中,我正在尝试创建一个索引页面,该页面将显示其所有子页面的列表以及与每个子页面关联的特色图像.
我在models.py中创建了这两个页面模型:
class IndexPage(Page):
    intro = RichTextField(blank=True)
    content_panels = Page.content_panels + [
        FieldPanel('intro', classname='full'),
    ]
    subpage_types = ['myapp.ItemPage']
class ItemPage(Page):
    representative_image = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+'
    )
    body = RichTextField(blank=True)
    promote_panels = Page.promote_panels + [
        ImageChooserPanel('representative_image'),
    ]
    content_panels = Page.content_panels + [
        FieldPanel('body', classname='full'),
    ]
在模板index_page.html中,我添加了以下代码:
<div class="intro">{{ self.intro|richtext }}</div>
{% for page in self.get_children %}
  {{ page.title }}
  {% image page.representative_image width-400 %}
{% endfor %}
这将显示所有子页面标题,但不显示图像.是否可以检索子页面的图像字段?
tim*_*ber 20
通常,检索页面查询集(例如
homepage.get_children())的操作会将它们作为基本页面实例返回,这些实例仅包含核心页面数据(如title).该specific()方法(例如homepage.get_children().specific())现在允许使用最少数量的查询来检索它们作为其最特定的类型.
因此,您不再需要在即将发布的1.1版中使用自定义功能,并且可以将模板更改为:
{% for page in self.get_children.specific %}
    {{ page.title }}
    {% image page.representative_image width-400 %}
{% endfor %}
至少从版本0.8开始,以下内容也可以使用specific:
{% for page in self.get_children %}
    {{ page.title }}
    {% image page.specific.representative_image width-400 %}
{% endfor %}
我找到了这个解决方案:向 IndexPage 添加一个函数 child_pages:
class IndexPage(Page):
    intro = RichTextField(blank=True)
    def child_pages(self):
        return ItemPage.objects.live().child_of(self)
    content_panels = Page.content_panels + [
        FieldPanel('intro', classname='full'),
    ]
    subpage_types = ['myapp.ItemPage']
这可以在模板中访问:
{% for page in self.child_pages %}
  {{ page.title }}
  {% image page.representative_image width-400 %}
{% endfor %}
| 归档时间: | 
 | 
| 查看次数: | 6055 次 | 
| 最近记录: |