以编程方式从本地计算机向Wagtail添加图像

问题描述

我正在尝试使用manage.py命令将图像添加到Wagtail网站上的模型中。我找到了this post that covers it,但它使用的是对来自互联网的图片的request.get()调用。我将图像保存在本地,并尝试使链接代码失败:

from django.core.files.images import ImageFile
from wagtail.images.models import Image

path = f"{img_directory}/{filename}"
img_bytes = open(path,"rb").read()
img_file = ImageFile(BytesIO(img_bytes),name=filename)
img_obj = Image(title=filename,file=img_file)
print(img_obj.file)
img_obj.save()

print(img_obj.file)语句确实按照定义打印文件名,但是当我尝试调用img_obj.save()时,出现以下错误

django.db.utils.IntegrityError: NOT NULL constraint Failed: wagtailimages_image.width

我猜我在打开文件时出错,并且没有按照我想要的方式将其读取为图像,但是我无法弄清楚我到底在哪里出错。

解决方法

https://github.com/wagtail/wagtail/blob/40aedfc66b6605d1ece80c15ec38b37f028082a8/wagtail/images/fields.py#L97

您可能可以这样做:

import willow
from django.core.files.images import ImageFile
from wagtail.images.models import Image

path = f"{img_directory}/{filename}"
img_bytes = open(path,"rb").read()
img_file = ImageFile(BytesIO(img_bytes),name=filename)

im = willow.Image.open(path)
width,height = im.get_size()

img_obj = Image(title=filename,file=img_file,width=width,height=height)
print(img_obj.file)
img_obj.save()