Skip to content

Commit 8458c08

Browse files
committed
PR feedback: implement form logic in serializer
1 parent a6c9b4d commit 8458c08

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

users/serializers.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from urllib.parse import urlparse
55

66
from django.conf import settings
7+
from django.core.files.uploadedfile import UploadedFile
78
from rest_framework import serializers
89

910
from core.validators import downscale_image_file_size_validator
@@ -111,6 +112,37 @@ def validate(self, data):
111112

112113
return super().validate(data)
113114

115+
def update(self, instance: User, validated_data):
116+
if validated_data.get("profile_image"):
117+
# If the user is uploading a new image file, we need to do a few special steps
118+
# 1. We need to set the image_uploaded flag correctly, to prevent automatic overwrites.
119+
# 2. We need to delete the old image from file storage, since it is not stored in memory.
120+
# 3. We need to delete their thumbnail to regenerate a new one.
121+
old_image = instance.profile_image
122+
old_image_name = old_image.name if old_image else None
123+
new_image_data = validated_data.get("profile_image")
124+
has_new_upload = isinstance(new_image_data, UploadedFile)
125+
126+
# Save the new image
127+
if not old_image:
128+
# reset image on image delete checked
129+
instance.image_uploaded = False
130+
elif has_new_upload and old_image_name:
131+
# Delete the old file directly from storage (not via FieldFile.delete(),
132+
# which closes file handles and interferes with the pending upload)
133+
old_image.storage.delete(old_image_name)
134+
135+
if has_new_upload:
136+
instance.profile_image = new_image_data
137+
instance.image_uploaded = True
138+
139+
instance.save()
140+
# Invalidate the cached thumbnail so ImageKit regenerates it
141+
if has_new_upload:
142+
instance.delete_cached_thumbnail()
143+
144+
return super().update(instance, validated_data)
145+
114146
class Meta:
115147
model = User
116148
fields = (

0 commit comments

Comments
 (0)