I'm following this tutorial for uploading (to S3 Amazon) and manipulating an image with Django. I'm stuck somewhere, because I'm able to upload the file, but whenever the method that should create the thumb is called, I think something's missed.
This is the code:
def upload_avatar_to(instance, filename):
import os
from django.utils.timezone import now
filename_base, filename_ext = os.path.splitext(filename)
return 'media/images/avatars/%s%s' % (
now().strftime("%Y%m%d%H%M%S"),
filename_ext.lower(),
)
class CustomUser(AbstractBaseUser, PermissionsMixin):
avatar = models.ImageField('profile picture', upload_to=upload_avatar_to, null=True, blank=True)
def save(self, *args, **kwargs):
super(CustomUser, self).save(*args, **kwargs)
self.create_avatar_thumb()
def create_avatar_thumb(self):
import os
from django.core.files.storage import default_storage as storage
if not self.avatar:
return ""
file_path = self.avatar.name
filename_base, filename_ext = os.path.splitext(file_path)
thumb_file_path = "%s_thumb.jpg" % filename_base
if storage.exists(thumb_file_path):
return "exists"
try:
f = storage.open(file_path, 'r')
image = Image.open(f)
width, height = image.size
if width > height:
delta = width - height
left = int(delta/2)
upper = 0
right = height + left
lower = height
else:
delta = height - width
left = 0
upper = int(delta/2)
right = width
lower = width + upper
image = image.crop((left, upper, right, lower))
image = image.resize((250, 250), Image.ANTIALIAS)
f_thumb = storage.open(thumb_file_path, "w")
image.save(f_thumb, "JPEG")
f_thumb.close()
return "success"
except:
return "error"
def get_avatar_thumb_url(self):
import os
from django.core.files.storage import default_storage as storage
if not self.avatar:
return ""
file_path = self.avatar.name
filename_base, filename_ext = os.path.splitext(file_path)
thumb_file_path = "%s_thumb.jpg" % filename_base
if storage.exists(thumb_file_path):
return storage.url(thumb_file_path)
return ""
It seems that everything's ok, but there should be something wrong with the code.
I upload the image, no errors are caught, but:
- The image doesn't get resized
- No "avatar-name_thumb.jpg" is created and uploaded on the bucket
What could I do?