ifiore
ifiore

Reputation: 470

How do I change how Wagtail serves media over it's API?

I'm currently trying to create a web application that uses Django + Wagtail for its backend content, and React for the frontend. As of now, upon pageload, I request all of the 'articles' from Wagtail via an http GET request. I then display this data in my frontend components.

This has worked well, except for one issue that I have, which is that media within the article body is represented as an <embed /> tag with a local source. What I'd like instead is an <img /> tag with the src pointing to the url that the image is stored in. How can I go about changing this on the backend? I can't seem to find any kind of documentation regarding this issue.

Here's what my get request response currently looks like:

{
    "id": 9,
    ...
    "title": "Child page",
    "date": null,
    "body": "<p>Here is a test image:</p><embed alt=\"testimg\" embedtype=\"image\" format=\"fullwidth\" id=\"5\"/><p></p>",
    "author": "Isaac"
}

Here's what I'd like it to look like:

{
    "id": 9,
    ...
    "title": "Child page",
    "date": null,
    "body": "<p>Here is a test image:</p><img src="image-location-url"/><p></p>",
    "author": "Isaac"
}

How should I go about this? Is this controllable with Wagtail settings configurations? Or should I be changing my Content model somehow? Thank you.

Upvotes: 1

Views: 413

Answers (1)

ifiore
ifiore

Reputation: 470

Copied straight from a comment on the Github page (https://github.com/wagtail/wagtail/issues/2695#issuecomment-373002412):

from wagtail.wagtailcore.rich_text import expand_db_html


class APIRichTextField(APIField):
    def __init__(self, name):
        serializer = serializers.APIRichTextSerializer()
        super().__init__(name=name, serializer=serializer)


class APIRichTextSerializer(fields.CharField):
    def to_representation(self, instance):
        representation = super().to_representation(instance)
        return expand_db_html(representation)

class MyModel(Page):
    body = RichTextField()
    api_fields = [
        APIRichTextField('body'),
    ]

Now my body is converted directly into the html that would be displayed on Wagtail's end. Thanks @solarissmoke for the guidance. If this answer/question doesn't follow guidelines please let me know and I'll happily delete this.

Upvotes: 1

Related Questions