How to resize source with sorl-thumbnail?
Sorl's ImageField
that you mention, is just a normal Django ImageField
with the added benefit of managing the deletion of cached thumbnails. There's no resizing done on the initial upload - that's something you have to implement yourself manually via the view you are using to upload. The docs show how to go about this. You can use sorl in that view to do the actual resize operation itself, using the low level API examlpes
EDIT
A quicker alternative is to just resize the image when the model is being saved using sorl. You can do something like the following (completely untested though!)
from sorl.thumbnail import get_thumbnail
class Foo(models.Model):
image = models.ImageField(upload_to...)
def save(self, *args, **kwargs):
if not self.id:
# Have to save the image (and imagefield) first
super(Foo, self).save(*args, **kwargs)
# obj is being created for the first time - resize
resized = get_thumbnail(self.image, "100x100" ...)
# Manually reassign the resized image to the image field
self.image.save(resized.name, resized.read(), True)
super(Foo, self).save(*args, **kwargs)
this will mean that you will have 2 versions of the same image on disk - one where the django image field decides to save it (upload_to
path) and one where sorl thumbnail has saved it's resized thumbnail. This, along with the fact the image is uploaded and saved twice, are the disadvantages of this approach. It's quicker to implement though
I found a flaw in the code above, got “str has no method chunck()”, if somebody want to use it. Here is my fix:
from sorl.thumbnail import get_thumbnail
from django.core.files.base import ContentFile
class Foo(models.Model):
image = models.ImageField(upload_to...)
def save(self, *args, **kwargs):
if not self.id:
super(Foo, self).save(*args, **kwargs)
resized = get_thumbnail(self.image, "100x100" ...)
self.image.save(resized.name, ContentFile(resized.read()), True)
super(Foo, self).save(*args, **kwargs)