From 4e76f88c3ca14ede342e7a073d712ba4bd2d0b8f Mon Sep 17 00:00:00 2001 From: Denis Cornehl Date: Thu, 5 Oct 2023 14:29:31 +0200 Subject: [PATCH 1/2] fix deepcopy & pickle for unsaved model instances & empty image fields --- stdimage/models.py | 8 ++++---- tests/test_models.py | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/stdimage/models.py b/stdimage/models.py index 6e0083d..dd429d8 100644 --- a/stdimage/models.py +++ b/stdimage/models.py @@ -158,9 +158,9 @@ def __getstate__(self): state = super().__getstate__() state["variations"] = {} for variation_name in self.field.variations: - variation = getattr(self, variation_name) - variation_state = variation.__getstate__() - state["variations"][variation_name] = variation_state + if variation := getattr(self, variation_name, None): + variation_state = variation.__getstate__() + state["variations"][variation_name] = variation_state return state def __setstate__(self, state): @@ -207,7 +207,7 @@ def __init__( render_variations=True, force_min_size=False, delete_orphans=False, - **kwargs + **kwargs, ): """ Standardized ImageField for Django. diff --git a/tests/test_models.py b/tests/test_models.py index e8d47f2..c5e74d9 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -1,5 +1,6 @@ import io import os +import pickle import time from copy import deepcopy @@ -174,6 +175,20 @@ def test_defer(self, db, django_assert_num_queries): deferred.image assert instance.image.thumbnail == deferred.image.thumbnail + @pytest.mark.django_db + def test_variations_deepcopy_unsaved(self): + instance_original = ResizeModel(image=self.fixtures["600x400.jpg"]) + instance = deepcopy(instance_original) + assert isinstance(instance.image, StdImageFieldFile) + assert instance.image == instance_original.image + + @pytest.mark.django_db + def test_variations_deepcopy_without_image(self): + instance_original = ThumbnailModel.objects.create(image=None) + instance = deepcopy(instance_original) + assert isinstance(instance.image, StdImageFieldFile) + assert instance.image == instance_original.image + @pytest.mark.django_db def test_variations_deepcopy(self): """Tests test_variations() with a deep copied object""" From 1cde8d2a6d1367b8f841f553d1a405656af6d145 Mon Sep 17 00:00:00 2001 From: Denis Cornehl Date: Thu, 19 Oct 2023 07:00:24 +0200 Subject: [PATCH 2/2] remove unused import --- tests/test_models.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/test_models.py b/tests/test_models.py index c5e74d9..e234521 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -1,6 +1,5 @@ import io import os -import pickle import time from copy import deepcopy