【问题标题】:wagtail set auto focal-point during upload鹡鸰在上传期间设置自动焦点
【发布时间】:2020-06-28 03:31:57
【问题描述】:

我注意到我们可以在 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'),

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

谢谢 阿穆尔

【问题讨论】:

    标签: django wagtail wagtail-streamfield wagtail-snippet


    【解决方案1】:

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

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

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

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

    了解如何调用信号处理程序注册函数很重要,我发现这个Stack Overflow answer 很有帮助。但是,将其添加到您的 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()
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2019-06-08
      相关资源
      最近更新 更多