SmileyChris / easy-thumbnails

Easy thumbnails for Django
http://easy-thumbnails.readthedocs.org/
BSD 3-Clause "New" or "Revised" License
1.39k stars 319 forks source link

Django ThumbnailerImageField upload_to as a function. Does NOT read "path". #507

Open stockersky opened 6 years ago

stockersky commented 6 years ago

Easy-thumbnails 2.5 Python 3.6.6 Django 2.1.1

In order to replace existing file when user update a image through an upload, I have successfully implemented the following solution on Django ImageField. However, it fails when using ThumbnailerImageField.

I got inspired by https://docs.djangoproject.com/en/2.1/ref/models/fields/#django.db.models.FileField.upload_to

Here is a simple example.

def picture_file_directory_path(instance, filename):
    import os
    try:
       # **here the path is wrong!** (read further this post for what it returns...)
        print("DEBUG!!! ---> {}".format(instance.picture_file.path))
        os.remove(instance.picture_file.path)
    except Exception as inst:
        print("DEBUG!!! ---> exception ---> {}".format(inst))
    return 'id-pics/id-img-{}.png'.format(instance.id)

class PersonalInfo(models.Model):  
     title = models.CharField(max_length=12, null=True, blank=True)
     picture_file = ThumbnailerImageField(upload_to=picture_file_directory_path, blank=True, null=True, resize_source=dict(size=(100, 130), target=(50,50), crop=True ))

When using ThumbnailerImageField, instance.picture_file.path will return a name based on the file that is being uploaded and the path is directly under MEDIA_ROOT. Something like this MY_MEDIA_ROOT/CIMG1349.JPG But the file is properly saved with the right path...

However, on other models, when using the classical ImageField, this works great. The ImageField 'path' is properly read and I can delete the file, so the new filename is kept the same. It seems that ThumbnailerImageField wraps ImageField in a way that cause this behavior.

Is this a bug? I did read many ways to cope with deleting updated files, but this is simple and should work, I guess.

Or maybe you could help me with a better way to cope with avoiding to fill the filesystem with orphaned files?