django-imagekit icon indicating copy to clipboard operation
django-imagekit copied to clipboard

ProcessedImageField and calculating hash in upload_to

Open a1tus opened this issue 5 years ago • 2 comments

Hello. Consider the situation. We have a model with photo = ProcessedImageField(processors=[ResizeToFit(100, 100)]) and dynamic upload_to arg where path is calculated as md5 for the uploaded image (quite typical behaviour).

The problem is that md5 hash that is calculated is using instance.photo but it holds original uploaded image but not the one that was passed through processors.

Temp fix below kinda works.

class PatchedProcessedImageFieldFile(ImageFieldFile):
    def save(self, name, content, save=True):
        filename, ext = os.path.splitext(name)
        spec = self.field.get_spec(source=content)
        ext = suggest_extension(name, spec.format)
        new_name = '%s%s' % (filename, ext)
        content = generate(spec)

        # PATCH: set generated file so that upload_to could use it
        # (`content` is File object)
        content.name = new_name
        setattr(self.instance, self.field.name, content)

        return super(PatchedProcessedImageFieldFile, self).save(new_name, content, save)


class PatchedProcessedImageField(ProcessedImageField):
    attr_class = PatchedProcessedImageFieldFile

May be it should be added to the master branch?

a1tus avatar Jan 19 '19 11:01 a1tus

I'm not sure if this patch will work with storages different than the local FS.

vstoykov avatar Jan 29 '19 00:01 vstoykov

All I do there is just set image field value with actual data. Don't quite get the point where it can fail, can you clarify please?

a1tus avatar Feb 02 '19 23:02 a1tus