Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ProcessedImageField and calculating hash in upload_to #483

Open
a1tus opened this issue Jan 19, 2019 · 2 comments
Open

ProcessedImageField and calculating hash in upload_to #483

a1tus opened this issue Jan 19, 2019 · 2 comments

Comments

@a1tus
Copy link
Contributor

a1tus commented Jan 19, 2019

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?

@vstoykov
Copy link
Collaborator

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

@a1tus
Copy link
Contributor Author

a1tus commented Feb 2, 2019

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants