代码之家  ›  专栏  ›  技术社区  ›  Daniel Erazo

如何将“嵌入”元素更改为富格文本图像Wagtail API响应中的“img”元素?

  •  0
  • Daniel Erazo  · 技术社区  · 3 年前

    我正在使用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 要素

    我什么都没试过,因为我不知道从哪里开始。

    0 回复  |  直到 3 年前
        1
  •  0
  •   regoawt    3 年前

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

    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()),