问题描述
我正在尝试使用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
我猜我在打开文件时出错,并且没有按照我想要的方式将其读取为图像,但是我无法弄清楚我到底在哪里出错。
解决方法
您可能可以这样做:
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()