以编程方式从本地计算机向 Wagtail 添加图像
Programatically adding an image to Wagtail from one's local machine
我正在尝试使用 manage.py
命令将图像添加到我的 Wagtail 网站上的模型。我找到了 this post that covers it,但它使用 requests.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()
我正在尝试使用 manage.py
命令将图像添加到我的 Wagtail 网站上的模型。我找到了 this post that covers it,但它使用 requests.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()