Skip to content

Commit dbbe8b4

Browse files
laymonagethibaudcolas
authored andcommitted
Add custom get_api_representation for CaptionedImageBlock
1 parent 9afc038 commit dbbe8b4

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

bakerydemo/base/blocks.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,17 @@
1212
from wagtail.images.blocks import ImageChooserBlock
1313

1414

15+
def get_image_api_representation(image):
16+
return {
17+
"id": image.pk,
18+
"title": image.title,
19+
"meta": {
20+
"type": type(image)._meta.label,
21+
"download_url": image.file.url,
22+
},
23+
}
24+
25+
1526
class CaptionedImageBlock(StructBlock):
1627
"""
1728
Custom `StructBlock` for utilizing images with associated caption and
@@ -34,6 +45,11 @@ def get_preview_value(self):
3445
"caption": self.preview_image.description,
3546
}
3647

48+
def get_api_representation(self, value, context=None):
49+
data = super().get_api_representation(value, context)
50+
data["image"] = get_image_api_representation(value["image"])
51+
return data
52+
3753
class Meta:
3854
icon = "image"
3955
template = "blocks/captioned_image_block.html"

bakerydemo/recipes/blocks.py

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,18 @@
1313
from wagtail.embeds.blocks import EmbedBlock
1414
from wagtail.images.blocks import ImageBlock
1515

16-
from bakerydemo.base.blocks import BlockQuote, HeadingBlock
16+
from bakerydemo.base.blocks import (
17+
BlockQuote,
18+
HeadingBlock,
19+
get_image_api_representation,
20+
)
21+
22+
23+
class CustomImageBlock(ImageBlock):
24+
def get_api_representation(self, value, context=None):
25+
data = super().get_api_representation(value, context)
26+
data["image"] = get_image_api_representation(value)
27+
return data
1728

1829

1930
class RecipeStepBlock(StructBlock):
@@ -57,7 +68,7 @@ class RecipeStreamBlock(StreamBlock):
5768
("text", CharBlock()),
5869
("numeric", FloatBlock()),
5970
("rich_text", RichTextBlock()),
60-
("image", ImageBlock()),
71+
("image", CustomImageBlock()),
6172
],
6273
group="Content",
6374
description=(
@@ -104,7 +115,7 @@ class RecipeStreamBlock(StreamBlock):
104115
},
105116
)
106117

107-
image_block = ImageBlock(group="Media")
118+
image_block = CustomImageBlock(group="Media")
108119
embed_block = EmbedBlock(
109120
help_text="Insert an embed URL e.g https://www.youtube.com/watch?v=SGJFWirQ3ks",
110121
icon="media",

0 commit comments

Comments
 (0)