Streamfield Custom API View

I have a few questions on this topic: https://groups.google.com/forum/#!topic/wagtail-developers/Z4oaCIJXYuI

I am creating a headless Wagtail with a React-based interface that calls the Wagtail API to parse JSON and display content. Pretty simple.

I was wondering if streamfield output can be configured in the break API. A few examples:

As I read in the topic above, the Wagtail v1 API was not ready for the custom Streamfield view in it. Has this changed since v2? (I didn’t notice anything on the change lists) If not, does anyone have any advice on how I could achieve this?

I already planned to create a custom image model to get the URL by calling api/v2/images/id, but I would like to get all this in one JSON 🤘 response.

Thank you very much in advance, Relations

+4
source share
3 answers

With Wagtail 1.9, you can change the presentation of the block API in StreamField by overriding the method get_api_representation()in the block.

In your example, we can override the method of ImageChooserBlock itself:

class ImageSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = wagtail.wagtailimages.get_image_model()
        fields = ['title', 'file', 'width', 'height', 'file_size']

class APIImageChooserBlock(ImageChooserBlock):
    def get_api_representation(self, value, context=None):
        return ImageSerializer(context=context).to_representation(value)

@wagtail.wagtailsnippets.models.register_snippet
class MySnippetForAPI(models.Model):
    title = models.CharField(max_length=80)
    content = StreamField([
        ('heading', blocks.CharBlock()),
        ('paragraph', blocks.RichTextBlock()),
        ('image', APIImageChooserBlock())
    ])

https://github.com/wagtail/wagtail/blob/b6ee2db6ac8dbf4b47a81f4b2684b7aca8cc2501/wagtail/wagtailcore/blocks/base.py#L244

+4

probabble, get_rendition StreamField, SerializerMethodField:

# serializers.py
# Explicitly importing since models are not loaded when serializers initialized

from wagtail.wagtailimages.models import Image as WagtailImage

class WagtailImageSerializer(serializers.ModelSerializer):
    url = serializers.SerializerMethodField()

    class Meta:
        model = WagtailImage
        fields = ['title', 'url']

    def get_url(self, obj):
        return obj.get_rendition('fill-300x186|jpegquality-60').url

# blocks.py

from .serializers import WagtailImageSerializer 

class APIImageChooserBlock(ImageChooserBlock):
    def get_api_representation(self, value, context=None):
        return WagtailImageSerializer(context=context).to_representation(value)

URL- .

+1

Source: https://habr.com/ru/post/1668385/


All Articles