4evertoblerone
4evertoblerone

Reputation: 95

Auto-filling other ImageFields based on the first one

I have to save 3 versions of uploaded photo (original one and two resized) and i don't want to use solr. Those two additional photos have to be represented as ImageFields in my model so i could use Django ORM.

class Post(models.Model):

    #...
    photo = models.ImageField(upload_to="photo_album")
    medium_photo = models.ImageField(upload_to="photo_album/medium", null=True)
    thumbnail = models.ImageField(upload_to="photo_album/thumbnails", null=True)

I have tried overriding save() method (photos in this case are the same size):

    def save(self):

        self.thumbnail.file = self.photo.file
        self.medium_photo.file = self.photo.file
        super(Post, self).save()

But it doesn't work(why?).

How can i auto-fill those additional ImageFields , in my model , before saving?

Any help is much appreciated! Thanks.

Upvotes: 0

Views: 63

Answers (2)

4evertoblerone
4evertoblerone

Reputation: 95

The correct way to fill other ImageField based on the first one (to create and save thumbnail based on the original photo in my case).

from PIL import Image
from django.core.files.base import ContentFile
import StringIO

class Post(models.Model):

    #...

    def save(self):

        thumb = Image.open(self.photo.file)
        thumb_io = StringIO.StringIO()
        thumb.save(thumb_io,format = thumb.format)
        self.thumbnail.save(self.photo.name, ContentFile(thumb_io.getvalue()), save=False)
        super(Post, self).save()

Don't forget to set save to False , otherwise it will start recursively adding same thumb over and over again.

Upvotes: 1

Hasan Ramezani
Hasan Ramezani

Reputation: 5194

remove .file from self.photo.file like this:

from PIL import Image
import StringIO

def save(self):
    iamge_file = StringIO.StringIO(self.photo.read())
    image = Image.open(image_file)
    self.thumbnail.file = image
    self.medium_photo.file = image
    super(Post, self).save()

Upvotes: 1

Related Questions