diff --git a/bookwyrm/preview_images.py b/bookwyrm/preview_images.py index 8224a2787..32465d6ed 100644 --- a/bookwyrm/preview_images.py +++ b/bookwyrm/preview_images.py @@ -317,15 +317,21 @@ def save_and_cleanup(image, instance=None): """Save and close the file""" if not isinstance(instance, (models.Book, models.User, models.SiteSettings)): return False - uuid = uuid4() - file_name = f"{instance.id}-{uuid}.jpg" image_buffer = BytesIO() try: try: - old_path = instance.preview_image.name + file_name = instance.preview_image.name except ValueError: - old_path = None + file_name = None + + if not file_name or file_name == "": + uuid = uuid4() + file_name = f"{instance.id}-{uuid}.jpg" + + # Clean up old file before saving + if file_name and default_storage.exists(file_name): + default_storage.delete(file_name) # Save image.save(image_buffer, format="jpeg", quality=75) @@ -345,10 +351,6 @@ def save_and_cleanup(image, instance=None): else: instance.save(update_fields=["preview_image"]) - # Clean up old file after saving - if old_path and default_storage.exists(old_path): - default_storage.delete(old_path) - finally: image_buffer.close() return True diff --git a/requirements.txt b/requirements.txt index 2cb1eec97..f308b43b9 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,7 @@ celery==4.4.2 colorthief==0.2.1 Django==3.2.5 -django-imagekit==4.0.2 +django-imagekit==4.1.0 django-model-utils==4.0.0 environs==9.3.4 flower==0.9.4