Redjam
Redjam

Reputation: 534

How to import posts from Wordpress to Wagtail 2 (Draftail editor) including images?

I'm trying to import posts from Wordpress to Wagtail including images.

I'm conscious about the fact that Draftail editor saves images with a dedicated tag, ex:

<embed alt="fonctionnement-pim-schema-640.png" embedtype="image" format="fullwidth" id="412" />

When I import my posts from Wordpress, I convert img tags to embed tags. Bellow a snippet of my code:

resp = requests.get(img["src"], stream=True)
if resp.status_code != requests.codes.ok:
    print("Unable to import " + img["src"])
    continue
fp = BytesIO()
fp.write(resp.content)
image = Image(title=file_name, width=width, height=height)
image.file.save(file_name, File(fp))
image.save()
try:
    embed_id = image.get_rendition("original").id
    embed_alt = image.get_rendition("original").alt
    new_tag = soup.new_tag('embed', alt=f'{embed_alt}', embedtype="image", format="fullwidth", id=f'{embed_id}')
    img.replace_with(new_tag)

It seems to work. When I check the database all img tags are replaced with a correctly formatted embed tag and all images are downloaded to the media folder.

Unfortunately, when I check the admin area. The embed tag exists but the image is not recognized:

Screenshot here

When I a use a generic embed tag in my import script (I mean without using "format" but the same embed code for all images) the import is working well (including within Draftail). Could "format" or "f string" introduce something wrong?

Any help would be much appreciated!

Thank in advance.

Upvotes: 1

Views: 206

Answers (1)

Redjam
Redjam

Reputation: 534

I found what was causing the issue.

I was using a rendition image to fetch the id:

embed_id = image.get_rendition("original").id

But rendition is for templates. In Draftail, we need to use the Image object id and not a rendition image id:

embed_id = image.id

For alt text, it's your call to choose something from your initial content.

Upvotes: 2

Related Questions