首页 > 解决方案 > 如何将帖子从 Wordpress 导入 Wagtail 2(Draftail 编辑器),包括图像?

问题描述

我正在尝试将帖子从 Wordpress 导入 Wagtail,包括图像。

我意识到 Draftail 编辑器使用专用标签保存图像的事实,例如:

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

当我从 Wordpress 导入我的帖子时,我将 img 标签转换为嵌入标签。下面是我的代码片段:

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)

它似乎工作。当我检查数据库时,所有img标签都替换为格式正确的嵌入标签,并且所有图像都下载到媒体文件夹中。

不幸的是,当我检查管理区域时。嵌入标签存在但无法识别图像:

截图在这里

当我在我的导入脚本中使用通用嵌入标签(我的意思是不使用“格式”但所有图像的嵌入代码相同)时,导入运行良好(包括在 Draftail 中)。“格式”或“f字符串”会引入错误吗?

任何帮助将非常感激!

预先感谢。

标签: pythondjangowordpresswagtail

解决方案


我找到了导致问题的原因。

我正在使用再现图像来获取 id:

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

但再现适用于模板。在 Draftail 中,我们需要使用 Image 对象 id 而不是再现图像 id:

embed_id = image.id

对于alt文本,您可以从初始内容中选择一些内容。


推荐阅读