Home > Blockchain >  wagtail how to JSON serialize RichText field in ListBlock
wagtail how to JSON serialize RichText field in ListBlock

Time:10-30

Error: Object of type RichText is not JSON serializable.

My code:

class AvvisiBlock(blocks.StructBlock):

avvisi = blocks.ListBlock(
    blocks.StructBlock(
        [
            ("title", blocks.CharBlock(classname="full title", icon="title", required=True)),
            ("text", blocks.RichTextBlock(icon="pilcrow", required=True)),
        ]
    )
)

def get_api_representation(self, value, context=None):
    dict_list = []
    for item in value["avvisi"]:
        print(item)
        temp_dict = {
            'title': item.get("title"),
            'text': item.get("text"),
        }
        dict_list.append(temp_dict)

    return dict_list

item in value:

StructValue([('title', 'avvisi importanti 1'), ('text', <wagtail.core.rich_text.RichText object at 0x000001F73FCDE988>)])

how can serialize the object?

CodePudding user response:

As described in Wagtail's rich text internals docs, there are two possible representations of rich text - the 'symbolic' source representation which keeps track of page links and other items such as images by their ID, and the rendered HTML version (which references them by URL, as you'd expect).

If you want the API to return the rendered HTML, use:

    temp_dict = {
        'title': item.get("title"),
        'text': str(item.get("text")),
    }

Or if you want it to return the symbolic source:

    temp_dict = {
        'title': item.get("title"),
        'text': item.get("text").source,
    }
  • Related