Wagtail - 在页面上呈现带有相关片段和标签的数据时遇到问题
Posted
技术标签:
【中文标题】Wagtail - 在页面上呈现带有相关片段和标签的数据时遇到问题【英文标题】:Wagtail - having trouble rendering data with related snippets and tags on a page 【发布时间】:2021-06-07 17:45:21 【问题描述】:我有以下代码用于 wagtail 页面
from django.db import models
from django import forms
from wagtail.admin.edit_handlers import FieldPanel, InlinePanel, MultiFieldPanel
from wagtail.core.models import Page, Orderable
from wagtail.images.models import Image
from wagtail.snippets.models import register_snippet
from modelcluster.fields import ParentalManyToManyField
@register_snippet
class GalleryCategory(models.Model):
name = models.CharField(max_length=255)
panels = [
FieldPanel('name'),
]
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'gallery categories'
class GalleryPage(Page):
"""
User can add images to the gallery via tags
"""
categories = ParentalManyToManyField('gallery.GalleryCategory', blank=True)
class Meta:
verbose_name_plural = 'Gallery Page'
content_panels = Page.content_panels + [
FieldPanel('categories', widget=forms.CheckboxSelectMultiple),
]
def get_context(self, request):
context = super().get_context(request)
category_images =
categories = self.categories.all()
for category in categories:
tagged_images = Image.objects.filter(
tagged_items__tag__name='gallery').filter(tagged_items__tag__name=category.name)
category_images[category.name] = tagged_images
context['category_images'] = category_images
return context
我很难让它在模板中呈现。
我试过这样做
% block content %
<h1> page.title </h1>
% if category_images %
% for category in category_images %
<p> category.name </p>
% for image in category.images %
<p>
image.title
% image image fill-320x240 %
</p>
% endfor %
% endfor %
% endif %
我也尝试了其他一些方法,尝试使用 categories.0、image.0、% for key,value in category %、% for key,value in image % 访问嵌套信息.我被困住了,如果有人能给我一些关于如何访问嵌套信息的指示,我将不胜感激。
【问题讨论】:
【参考方案1】:您的 category_images
变量是一个字典,将类别名称映射到图像列表,您可以使用 category_images.items
对其进行循环,这将为您返回一系列 (name, list_of_images) 对:
% for name, images in category_images.items %
<p> name </p>
% for image in images %
<p>
image.title
% image image fill-320x240 %
</p>
% endfor %
% endfor %
【讨论】:
以上是关于Wagtail - 在页面上呈现带有相关片段和标签的数据时遇到问题的主要内容,如果未能解决你的问题,请参考以下文章