Wagtail 增加了对 Collections with hierarchy in 2.11 (November 2020) 的支持。
这可以实现最初的目标,即提供一种更简单的方法来选择一组更易于维护的图像。该方法在 Wagtail bakery 演示应用程序中用于同样的目的 (see GalleryPage)。
代码示例
下面是sn-ps实现类似方法的相关代码。
models.py
from django import forms
from django.db import models
from wagtail.admin.edit_handlers import FieldPanel
from wagtail.core.models import Collection, Page
from wagtail.images import get_image_model
class CustomSelect(forms.Select):
"""Allow for visual representation of 'depth' of collection in select"""
def create_option(self, name, value, *args, **kwargs):
option_dict = super().create_option(name, value, *args, **kwargs)
instance = getattr(value, 'instance', None)
if instance:
option_dict['label'] = instance.get_indented_name()
return option_dict
class GalleryPage(Page):
collection = models.ForeignKey(
Collection,
limit_choices_to=~models.Q(name__in=['Root']), # do not allow 'root' selection
null=True,
blank=True,
on_delete=models.SET_NULL,
help_text='Select the image collection for this gallery.'
)
content_panels = Page.content_panels + [
FieldPanel('collection', widget=CustomSelect),
# ... other panels
]
def get_collection_images(self):
return get_image_model().objects.filter(collection=self.collection)
gallery_page.html
{% extends "base.html" %}
{% load wagtailimages_tags %}
{% block content %}
<div class="row">
{% for img in page.get_collection_images %}
{% image img fill-285x200-c100 as img_obj %}
<div class="col-sm-6">
<figure class="gallery-figure">
<img src="{{img_obj.url}}" class="img-responsive" />
<figcaption>{{ img.title }}</figcaption>
</figure>
</div>
{% endfor %}
</div>
{% endblock content %}