Handling files in Django

1.5k views Asked by At

I'm using ImageMagick and the binding wand to generate thumbnails for uploaded images in Django. I can generate the thumbnail fine, but I'm uncertain about how to go about passing the image object from ImageMagick back into the Django model. So I have a simplified model as below:

from wand import Image

class Attachment(models.Model):
    attachment = models.FileField(upload_to="some_path")
    thumbnail = models.ImageField(upload_to="other_path")

    def generate_thumb(self):
        with Image(file=self.attachment) as wand:
            thumb = wand.resize(width=50, height=50)
            thumb.save(file=self.thumbnail)

This generates an error at the last line of ValueError: The 'thumbnail' attribute has no file associated with it. Is there a simple way to get a file object out of wand and into django without too much silliness?

Thanks.

2

There are 2 answers

1
minhee On

Disclaimer: I am the creator of Wand you are trying to use.

First of all, ImageField requires PIL. It means you don’t need Wand, because you probably already installed an another image library. However I’ll answer to your question without any big changes.

It seems that self.thumbnail was not initialized yet at the moment, so you have to create a new File or ImageFile first:

import io

def generate_thumb(self):
    buffer = io.BytesIO()
    with Image(file=self.attachment) as wand:
        wand.resize(width=50, height=50)
        wand.save(file=buffer)
    buffer.seek(0)
    self.thumbnail = ImageFile(buffer)

Plus, from wand import Image will raise ImportError. It should be changed:

from wand.image import Image
0
Francis Yaconiello On

If the goal is easy thumbnails in your django app try: https://github.com/sorl/sorl-thumbnail

Its pretty popular and active.