Let's see how we can add an image to Wagtail from within Python code.
In Wagtail, images are managed by the
Image class. Let's start with checking how to get the list of images which are already uploaded:
from wagtail.images.models import Imagefor img in Image.objects.all():print(img.title, img.get_file_hash())
To upload an image, it takes a bit more steps:
image_file = ImageFile(open(file_path, 'rb'), name=name)image = Image(title=name, file=image_file)image.save()
So, we first create an
ImageFile instance (this is a standard Django class. To create the instance, we need a file object, hence the
open statement. Make sure you read the file in binary mode using the
rb argument. We also need a name for the uploaded image.
ImageFile instance, we can then create an
Image instance with the file as the argument, optionally specifying the image title.
To persist it into the database, all we need to do is to call the