From 17378e06c8307600841d0e180e2729ea61025b9d Mon Sep 17 00:00:00 2001 From: "Storm B. Heg" Date: Wed, 13 Nov 2024 23:33:06 +0100 Subject: [PATCH] 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 --- wagtail/images/blocks.py | 16 +++++++++------- wagtail/images/tests/test_blocks.py | 5 +++++ 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/wagtail/images/blocks.py b/wagtail/images/blocks.py index 974e3447bf..ca1b3d2169 100644 --- a/wagtail/images/blocks.py +++ b/wagtail/images/blocks.py @@ -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 ] diff --git a/wagtail/images/tests/test_blocks.py b/wagtail/images/tests/test_blocks.py index 389ec98d15..6878678855 100644 --- a/wagtail/images/tests/test_blocks.py +++ b/wagtail/images/tests/test_blocks.py @@ -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])