1

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

我正在尝试在上传最大 200*220px 期间添加一个自动焦点。

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

从 django.db 导入模型

从 wagtail.images.models 导入 Image、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'),

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

谢谢阿纳穆尔

4

1 回答 1

1

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

Wagtail 中已经使用的一个很好的例子是特征检测系统,如果检测到人脸,它将在保存时自动添加一个焦点。

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

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

了解如何调用信号处理程序注册函数很重要,我发现这个Stack Overflow 答案很有帮助。但是,将它添加到您的wagtail_hooks.py文件中可能会更简单,因为您知道它将在正确的时间运行(当应用程序准备好并加载模型时。

如果您不想依赖这种方法,您可以在Django 文档中阅读更多 app.ready() 文档。wagtail_hooks.py

示例实现

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()

于 2020-06-28T05:41:03.967 回答