3

What i want: when user download photo from the admin's panel, I want create a preview(thumbnail) and save it into other field of this model, using sorl.thumbnail.

What i do:

from sorl.thumbnail import ImageField, get_thumbnail

class sitePhotos(models.Model):

    photo = ImageField(verbose_name=u'Фотография для галереи', 
               upload_to=upload_galery_photos, null=True)

    preview = ImageField(upload_to=upload_galery_previews, editable=False, null=True)

Migrations are doing.

I was trying overwrite save method from class sitePhotos:

def save(self, *args, **kwargs):
    self.preview = get_thumbnail(self.photo, '250x250', crop='center', quality=99)
    super(sitePhotos, self).save(*args, **kwargs)

Problems: Documentation sorl.thumbnail: https://sorl-thumbnail.readthedocs.io/en/latest/examples.html#low-level-api-examples

im = get_thumbnail(my_file, '100x100', crop='center', quality=99)

What's type of my_file? It is a url, ImageField or what? When start has error 'ImageField' object has no attribute '_committed'

Google: override save method - 'ImageFile' object has no attribute '_committed'

After that i have magic with urls and other. My finish function:

self.preview = get_thumbnail('../'+self.photo.url, '250x250',
                            crop='center', quality=99).url

May be somebody has working example of this or where can I read about this? Thank you for your answers!

Davit Tovmasyan
  • 3,238
  • 2
  • 20
  • 36

1 Answers1

-1

You can use the save method on Image file:

def save(self, *args, **kwargs):
    preview = get_thumbnail(self.photo, '250x250', crop='center', quality=99)
    self.preview.save(preview.name, ContentFile(preview.read()), save=False)
    super(sitePhotos, self).save(*args, **kwargs)
Uyen Do
  • 9
  • 2