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

Keep oringinal ImageField and copy of ProcessedImageField

Open mzu opened this issue 10 years ago • 3 comments

Hi, I was wondering if it is possible to do the following with a Model like this:

class TestImage(models.Model):
      original = models.ImageField(max_length=255, upload_to=get_upload_to)
      thumbnail = ProcessedImageField(upload_to=get_thumbnail_upload_to,
                                      processors=[Transpose(), ResizeToFill(99, 128)],
                                      format='JPEG',
                                      options={'quality': 80},
                                      null=True)

I want to keep the original field as a ImageField but would like to create a thumbnai during the upload. I am not sure how to achieve this. One of my restrictions is that any uploaded images can only get accessed via a view that checks permissions and then creates a HttpResponse with a X-Accel-Redirect to tell Nginx that access to the upload folder is allowed.

So the normal approach of using ImageSpecField would not work for me. I need the tumbnail version written to disk. Is there a way to save the file to the original field while also creating a ProcessedImageField for thumbnail?

mzu avatar Sep 28 '15 15:09 mzu

Here is an update for a possible solution to this. I ended up using a hidden form element for the thumbnail and just copied request.FILES['thumbnail'] = request.FILES.get('original') before initialising the form. This seems to do the job.

mzu avatar Sep 28 '15 19:09 mzu

There shouldn't be any problem with keeping the original field an ImageField. If you want to control when the image spec file is generated, you can do that with cache file strategies. In other words, ImageSpecField should work fine, so long as you configure it the way you want.

matthewwithanm avatar Sep 30 '15 03:09 matthewwithanm

@mzu This approach will not work always because you need to have extra field in the form that you will not use and extra work in the view before initializing the form.

Another solution will be to overwrite the save method of your model and do something like this:

def save(self, *args, **kwargs):
    if not self.original._committed:
        self.thumbnail = self.original.file
    super().save(*args, **kwargs)

This will ensure that even when you change the file not from your custom view (form example from django admin) the thumbnail will also be updated.

If you have found a solution for your problem we can close this issue. Do you think that the issue must be closed?

vstoykov avatar Dec 08 '15 20:12 vstoykov