I'm trying to add images to a model on my Wagtail site with a manage.py command. I found this post that covers it, but it's using a requests.get() call to the image from the internet. I have my images saved locally and have tried to adapt the linked code unsuccessfully:
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()
The print(img_obj.file) statement does print the filename as defined, but when I try to call img_obj.save(), I get the following error:
django.db.utils.IntegrityError: NOT NULL constraint failed: wagtailimages_image.width
I'm guessing that I'm opening the file wrong and it's not reading it as an image as I want it to, but I can't figure out where exactly I'm going wrong.
Look at https://github.com/wagtail/wagtail/blob/40aedfc66b6605d1ece80c15ec38b37f028082a8/wagtail/images/fields.py#L97
You could probably do:
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With