#django #python #wagtail
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:
1from wagtail.images.models import Image 2 3for img in Image.objects.all(): 4 print(img.title, img.get_file_hash())
To upload an image, it takes a bit more steps:
1image_file = ImageFile(open(file_path, 'rb'), name=name) 2image = Image(title=name, file=image_file) 3image.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
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.