Wagtail父页面模板无法访问子页面可排序属性的问题
解决Wagtail父页面遍历子页面时无法访问自定义字段的问题
问题核心:page.get_children()返回的是Wagtail基础Page对象,而非你自定义的子页面模型实例,因此无法直接访问子页面的gallery_images这类自定义字段。
解决方案
在模板中通过specific方法将基础Page对象转换为实际的子页面模型实例,即可访问自定义字段。
修改后的代码示例
{% for post in page.get_children %} {% with post=post.specific %} <div class="max-w-sm bg-white border border-gray-200 rounded-lg shadow dark:bg-gray-800 dark:border-gray-700"> <a href="{% pageurl post %}"> {% for item in post.gallery_images.all %} {% image item.image fill-320x240 as img %} <img alt="{{ item.caption }}" class="block h-full w-full rounded-lg object-cover object-center" src="{{ img.url }}" /> <img class="rounded-t-lg" src="{{ img.url }}" alt="{{ item.caption }}" class="carousel-img"/> <p class="mb-3 font-normal text-gray-700 dark:text-gray-400">{{ img.url }}</p> {% endfor %} </a> <div class="p-5"> <a href="{% pageurl post %}"> <h5 class="mb-2 text-2xl font-bold tracking-tight text-gray-900 dark:text-white">{{ post.title }}</h5> </a> <p class="mb-3 font-normal text-gray-700 dark:text-gray-400">Here are the biggest enterprise technology acquisitions of 2021 so far, in reverse chronological order.</p> <a href="#" class="inline-flex items-center px-3 py-2 text-sm font-medium text-center text-white bg-blue-700 rounded-lg hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"> Read more <svg aria-hidden="true" class="w-4 h-4 ml-2 -mr-1" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M10.293 3.293a1 1 0 011.414 0l6 6a1 1 0 010 1.414l-6 6a1 1 0 01-1.414-1.414L14.586 11H3a1 1 0 110-2h11.586l-4.293-4.293a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg> </a> </div> </div> {% endwith %} {% endfor %} </div>
关键说明
post.specific会将基础Page对象转换为对应的子页面模型(比如你的PostPage),这样就能访问gallery_images这类自定义字段。- 如果父页面下有多种类型的子页面,可以通过
post.specific_class判断类型后再处理,比如:{% if post.specific_class == PostPage %} {# 处理PostPage类型的子页面 #} {% endif %}
内容的提问来源于stack exchange,提问作者glls
相关产品推荐
相关产品推荐

