You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Wagtail图片编辑时裁剪信号失效问题及修复方案

Wagtail图片裁剪信号在编辑页面失效的解决方案

问题

自定义的图片裁剪信号在图片上传时正常工作,但在Wagtail的wagtail.images.views.images.edit页面修改图片时无法触发生效。

修复代码

更新项目中的wagtail.hooks.py文件,替换为以下代码:

from django.db.models.signals import post_save
from django.shortcuts import get_object_or_404
from wagtail.images.models import get_image_model
import os

@receiver(post_save, sender=get_image_model())
def resize_images_on_upload_or_edit(sender, instance, **kwargs):
    # 判断图片尺寸是否超过2000px,或文件大小超过500KB
    if (instance.width > 2000 or instance.height > 2000) or instance.file_size > 500_000:
        try:
            # 确认实例存在
            if get_object_or_404(sender, pk=instance.pk):
                # 生成指定规格的缩略图(裁剪/缩放)
                croped_image = instance.get_rendition('max-2000x2000|jpegquality-80')
                croped_file = croped_image.file.path
                
                if os.path.exists(croped_file):
                    # 更新图片实例的尺寸和文件大小信息
                    instance.width = croped_image.width
                    instance.height = croped_image.height
                    instance.file_size = os.path.getsize(croped_file)
                    
                    original_file = instance.file.path
                    # 删除原文件,将裁剪后的文件替换为原文件
                    os.remove(original_file)
                    instance.save()
                    
                    try:
                        os.rename(croped_file, original_file)
                    except FileExistsError as e:
                        os.replace(croped_file, original_file)
                        print(e)
        except IOError as e:
            print(e)

关键说明

原代码中的条件判断(instance.width and instance.height) > 2000存在逻辑错误,会导致尺寸判断不生效,修复为(instance.width > 2000 or instance.height > 2000)后,无论宽或高超过2000px都会触发裁剪,同时保留了文件大小超过500KB的判断条件。


内容的提问来源于stack exchange,提问作者Jordano Bruno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 20:42:36