In your models.py:
================================
from PIL import Image
import glob, os
thumb_size = 90, 90
class MyClass(models.Model):
foto = models.ImageField(upload_to='my_photos/',blank=True)
def save(self):
file_path = self.get_foto_filename()
# is there a photo?
if (file_path):
file, ext = os.path.splitext(file_path)
im = Image.open(file_path)
# thanks to PIL ;)
im.thumbnail(thumb_size, Image.ANTIALIAS)
# save thumbnail
im.save(file + ".thumbnail.jpg", "JPEG")
super(MyClass, self).save()
def delete(self):
file_path = self.get_foto_filename()
# There's is a file?
if (file_path):
file, ext = os.path.splitext(file_path)
thumb = file + ".thumbnail.jpg"
# if there is a thumb we delete it
if(thumb):
os.remove(thumb)
super(Artista, self).delete()
def show_thumb(self):
# get the url of the file
file_path = self.get_foto_url()
# add .thumbnail between file and extension
file, ext = os.path.splitext(file_path)
file = file + ".thumbnail.jpg"
if(file_path):
return "<a href=\"%s\" target=\"_blank\"><img src=\"%s\"
border=\"0\" /></a>" % (file_path,file)
mostrar_thumb.allow_tags = True
mostrar_thumb.short_description='Foto'
class Admin:
list_display = ('show_thumb',)
==================================
That's all. If you make any improvements let me know them ;)
I needed to make this and I hope it helps some people there. Features:- Generate thumbs from ImageFields when creating the models(file.jpg -> thumbnail saved as: file.thumbnail.jpg)- Showing thumbs in admin- Deleting thumbs when deleting the objectIn your models.py:================================from PIL import Imageimport glob, osthumb_size = 90, 90class MyClass(models.Model):foto = models.ImageField(upload_to='my_photos/',blank=True)def save(self):file_path = self.get_foto_filename()# is there a photo?
#if (file_path):
file, ext = os.path.splitext(file_path)im = Image.open(file_path)# thanks to PIL ;)im.thumbnail(thumb_size, Image.ANTIALIAS)# save thumbnailim.save(file + ".thumbnail.jpg", "JPEG")super(MyClass, self).save()def delete(self):file_path = self.get_foto_filename()# There's is a file?
# if (file_path):