Skip to content

Commit bc9af2a

Browse files
authored
Fix deepcopy & pickle for unsaved model instances & empty image fields (#324)
1 parent a1427a5 commit bc9af2a

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

stdimage/models.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -158,9 +158,9 @@ def __getstate__(self):
158158
state = super().__getstate__()
159159
state["variations"] = {}
160160
for variation_name in self.field.variations:
161-
variation = getattr(self, variation_name)
162-
variation_state = variation.__getstate__()
163-
state["variations"][variation_name] = variation_state
161+
if variation := getattr(self, variation_name, None):
162+
variation_state = variation.__getstate__()
163+
state["variations"][variation_name] = variation_state
164164
return state
165165

166166
def __setstate__(self, state):
@@ -207,7 +207,7 @@ def __init__(
207207
render_variations=True,
208208
force_min_size=False,
209209
delete_orphans=False,
210-
**kwargs
210+
**kwargs,
211211
):
212212
"""
213213
Standardized ImageField for Django.

tests/test_models.py

+14
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,20 @@ def test_defer(self, db, django_assert_num_queries):
174174
deferred.image
175175
assert instance.image.thumbnail == deferred.image.thumbnail
176176

177+
@pytest.mark.django_db
178+
def test_variations_deepcopy_unsaved(self):
179+
instance_original = ResizeModel(image=self.fixtures["600x400.jpg"])
180+
instance = deepcopy(instance_original)
181+
assert isinstance(instance.image, StdImageFieldFile)
182+
assert instance.image == instance_original.image
183+
184+
@pytest.mark.django_db
185+
def test_variations_deepcopy_without_image(self):
186+
instance_original = ThumbnailModel.objects.create(image=None)
187+
instance = deepcopy(instance_original)
188+
assert isinstance(instance.image, StdImageFieldFile)
189+
assert instance.image == instance_original.image
190+
177191
@pytest.mark.django_db
178192
def test_variations_deepcopy(self):
179193
"""Tests test_variations() with a deep copied object"""

0 commit comments

Comments
 (0)