|
4 | 4 | from urllib.parse import urlparse |
5 | 5 |
|
6 | 6 | from django.conf import settings |
| 7 | +from django.core.files.uploadedfile import UploadedFile |
7 | 8 | from rest_framework import serializers |
8 | 9 |
|
9 | 10 | from core.validators import downscale_image_file_size_validator |
@@ -111,6 +112,37 @@ def validate(self, data): |
111 | 112 |
|
112 | 113 | return super().validate(data) |
113 | 114 |
|
| 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 | + |
114 | 146 | class Meta: |
115 | 147 | model = User |
116 | 148 | fields = ( |
|
0 commit comments