@@ -114,15 +114,19 @@ def validate(self, data):
114114 return super ().validate (data )
115115
116116 def update (self , instance : User , validated_data ):
117- if validated_data .get ("profile_image" ):
117+ # Pop the image and apply the file-lifecycle steps ourselves. If we left
118+ # it in validated_data, the parent update() would assign and save it a
119+ # second time, writing a duplicate file to storage and orphaning one.
120+ new_image_data = validated_data .pop ("profile_image" , None )
121+ has_new_upload = isinstance (new_image_data , UploadedFile )
122+
123+ if new_image_data :
118124 # If the user is uploading a new image file, we need to do a few special steps
119125 # 1. We need to set the image_uploaded flag correctly, to prevent automatic overwrites.
120126 # 2. We need to delete the old image from file storage, since it is not stored in memory.
121127 # 3. We need to delete their thumbnail to regenerate a new one.
122128 old_image = instance .profile_image
123129 old_image_name = old_image .name if old_image else None
124- new_image_data = validated_data .get ("profile_image" )
125- has_new_upload = isinstance (new_image_data , UploadedFile )
126130
127131 # Save the new image
128132 if not old_image :
@@ -137,12 +141,15 @@ def update(self, instance: User, validated_data):
137141 instance .profile_image = new_image_data
138142 instance .image_uploaded = True
139143
140- instance .save ()
141- # Invalidate the cached thumbnail so ImageKit regenerates it
142- if has_new_upload :
143- instance .delete_cached_thumbnail ()
144+ # Applies the remaining fields and persists everything set above
145+ # (image + flags) in a single save.
146+ instance = super ().update (instance , validated_data )
147+
148+ # Invalidate the cached thumbnail so ImageKit regenerates it
149+ if has_new_upload :
150+ instance .delete_cached_thumbnail ()
144151
145- return super (). update ( instance , validated_data )
152+ return instance
146153
147154 class Meta :
148155 model = User
0 commit comments