wagtail 在上传过程中设置自动焦点

wagtail set auto focal-point during upload

我注意到我们可以在此处为鹡鸰设置自定义图像模型:https://docs.wagtail.io/en/v2.9/advanced_topics/images/custom_image_model.html

我正在尝试在最大 200*220 像素的上传过程中添加一个自动焦点。

我按照上面的文档尝试了很多。

从 django.db 导入模型

从 wagtail.images.models 导入图像、AbstractImage、AbstractRendition

class CustomImage(AbstractImage):
    # Add any extra fields to image here

    # eg. To add a caption field:
    # caption = models.CharField(max_length=255, blank=True)

    admin_form_fields = Image.admin_form_fields + (
        # Then add the field names here to make them appear in the form:
        # 'caption',
    )


class CustomRendition(AbstractRendition):
    image = models.ForeignKey(CustomImage, on_delete=models.CASCADE, related_name='renditions')

    class Meta:
        unique_together = (
            ('image', 'filter_spec', 'focal_point_key'),

谁能帮我完成自定义焦点的设置?

谢谢 阿纳穆尔

您可能不需要自定义 image 模型来实现此目标,Django 有一个名为 signals 的内置系统。这使您可以监听任何现有 Django 模型的创建和编辑(以及其他),并在将数据保存到数据库之前修改数据。

Wagtail 中已经使用的一个很好的例子是 feature detection 系统,如果检测到面部,它会在保存时自动添加一个焦点。

您可以在源代码中看到这是如何实现的,wagtail/images/signal_handlers.py

您可能需要了解如何建立焦点,具体取决于您希望如何计算它,但基本上您需要在图像实例上调用 set_focal_point。必须为该方法提供一个 Rect 的实例,该实例可在 images/rect.py.

的源代码中找到

了解如何调用您的信号处理程序注册函数很重要,我发现了这个 Stack Overflow answer to be helpful. However, it might be simpler to just add it to your wagtail_hooks.py 文件,如您所知,它将在正确的时间 运行(当应用程序准备就绪时 &模型已加载。

如果您不想依赖 wagtail_hooks.py 方法,可以在 Django docs for app.ready() 阅读更多内容。

示例实现

myapp/signal_handlers.py
from django.db.models.signals import pre_save

from wagtail.images import get_image_model
from wagtail.images.rect import Rect


def pre_save_image_add_auto_focal_point(instance, **kwargs):
    # Make sure the image doesn't already have a focal point
    # add any other logic here based on the image about to be saved

    if not instance.has_focal_point():
        # this will run on update and creation, check instance.pk to see if this is new

        # generate a focal_point - via Rect(left, top, right, bottom)
        focal_point = Rect(15, 15, 150, 150)

        # Set the focal point
        instance.set_focal_point(focal_point)


def register_signal_handlers():
    # important: this function must be called at the app ready

    Image = get_image_model()

    pre_save.connect(pre_save_image_add_auto_focal_point, sender=Image)

myapp/wagtail_hooks.py
from .signal_handlers import register_signal_handlers


register_signal_handlers()