Daniel Erazo
Daniel Erazo

Reputation: 95

How can I change `embed` element for `img` element in rich text image Wagtail API response?

I'm using the Wagtail API to retrieve data of the pages from my site. The problem I'm having is that when there is an image inside a rich text block and I retrieve it using the API, the body attribute has the shape:

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

It means, the API returns an embed element instead of an img element with the source of the image, I want to change this response by having the img element.

I haven't tried anything yet because I don't know where to start.

Upvotes: 1

Views: 112

Answers (3)

MeganM
MeganM

Reputation: 56

I'm using rest_framework to manage the API. Here's how I did it, added to serializers.py:

from rest_framework import serializers
from rest_framework.fields import CharField
from wagtail.rich_text import expand_db_html
from .model import MyModel

class RichTextHTMLSerializer(CharField):
    def to_representation(self, value):
        return expand_db_html(value)


class MyModelSerializer(serializers.ModelSerializer):
    appicable_field = RichTextHTMLSerializer()

    class Meta:
        model = FAQ
        fields = ["appicable_field"]

Upvotes: 0

Ramon de Jesus
Ramon de Jesus

Reputation: 788

This is how I solved it:

Create a new RichTextBlock like so:

class APIRichTextBlock(blocks.RichTextBlock):
    # Convert Wagtail's <embed> to <img> for API usage
    def get_api_representation(self, value, context=None):
        return expand_db_html(value.source)

Use this APIRichTextBlock instead of blocks.RichTextBlock like so:

class ContentBlock(blocks.StreamBlock):
    ...
    text_block = APIRichTextBlock()

Now in your API response the <embed> is replaced by a <img>.

Upvotes: 0

regoawt
regoawt

Reputation: 301

I resolved it by adding a custom serializer:

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)

and then pointing to it from the APIField in the model definition:

APIField("body", serializer=BlogPostBodySerializer()),

Upvotes: 0

Related Questions