0
0
mirror of https://github.com/wagtail/wagtail.git synced 2024-11-21 18:09:02 +01:00

Refactor ImageBlock.bulk_to_python to handle more cases of bad data

Specifically, cases where an ImageChooserBlock to ImageBlock migration
results in `[None]` as a value.

ref: https://github.com/wagtail/wagtail/issues/12514
This commit is contained in:
Storm B. Heg 2024-11-13 23:33:06 +01:00 committed by Matt Westcott
parent f4d3c80e2f
commit 17378e06c8
2 changed files with 14 additions and 7 deletions

View File

@ -148,9 +148,16 @@ class ImageBlock(StructBlock):
def bulk_to_python(self, values):
values = list(values)
if any(isinstance(value, int) for value in values):
# `values` is a list of image IDs (as we might encounter if an ImageChooserBlock has been
# The normal case: `values` is a list of dicts. This is the normal representation of this block.
if all(isinstance(value, dict) for value in values):
# `values` is a list of dicts containing `image`, `decorative` and `alt_text` keys
struct_values = super().bulk_to_python(values)
# Else we are in a fallback for backwards compatibility with ImageChooserBlock
else:
# `values` might be a list of image IDs (as we might encounter if an ImageChooserBlock has been
# changed to an ImageBlock with no data migration)
# Or it could be a [None] if we are coming from an empty ImageChooserBlock
image_values = self.child_blocks["image"].bulk_to_python(values)
struct_values = [
@ -162,11 +169,6 @@ class ImageBlock(StructBlock):
for image in image_values
]
else:
# assume `values` is a (possibly empty) list of dicts containing
# `image`, `decorative` and `alt_text` keys to be handled by the StructBlock superclass
struct_values = super().bulk_to_python(values)
return [
self._struct_value_to_image(struct_value) for struct_value in struct_values
]

View File

@ -253,6 +253,11 @@ class TestImageBlock(TestImageChooserBlock):
result = block.bulk_to_python([])
self.assertEqual(result, [])
def test_bulk_to_python_with_list_of_none(self):
block = ImageBlock(required=False)
result = block.bulk_to_python([None])
self.assertEqual(result, [None])
def test_bulk_to_python_with_list_of_ints(self):
block = ImageBlock(required=False)
result = block.bulk_to_python([None, self.image.id, self.image.id])