如何在富文本图像 Wagtail API 响应中将“embed”元素更改为“img”元素?

问题描述 投票:0回答:1

我正在使用 Wagtail API 从我的网站检索页面数据。我遇到的问题是,当富文本块内有图像并且我使用 API 检索它时,body 属性的形状为:

"body": [
        {
            "type": "rich_text",
            "value": "<p>some text</p>\n<p><embed alt=\"Some alt text"\" embedtype=\"image\" format=\"fullwidth\" id=\"68810\"/></p>"
        },

这意味着,API 返回一个

embed
元素,而不是带有图像源的
img
元素,我想通过使用
img
元素来更改此响应。

我还没有尝试过任何东西,因为我不知道从哪里开始。

wagtail wagtail-apiv2
1个回答
0
投票

我通过添加自定义序列化器解决了这个问题:

from rest_framework.fields import ReadOnlyField
from wagtail.rich_text import expand_db_html


class BlogPostBodySerializer(ReadOnlyField):
    def to_representation(self, instance):
        representation = super().to_representation(instance)
        return expand_db_html(representation)

然后从模型定义中的 APIField 指向它:

APIField("body", serializer=BlogPostBodySerializer()),
© www.soinside.com 2019 - 2024. All rights reserved.