代码是这样的:
class Document(models.Model):
docfile = models.FileField(upload_to='documents/big/')
thumbnail = models.FileField(upload_to='documents/small/')
def create_thumbnail(self):
if not self.image:
return
from PIL import Image
from cStringIO import StringIO
from django.core.files.uploadedfile import SimpleUploadedFile
import os
THUMBNAIL_SIZE = (200,200)
DJANGO_TYPE = self.image.file.content_type
if DJANGO_TYPE == 'image/jpeg':
PIL_TYPE = 'jpeg'
FILE_EXTENSION = 'jpg'
elif DJANGO_TYPE == 'image/png':
PIL_TYPE = 'png'
FILE_EXTENSION = 'png'
image = Image.open(StringIO(self.image.read()))
image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
temp_handle = StringIO()
image.save(temp_handle, PIL_TYPE)
temp_handle.seek(0)
suf = SimpleUploadedFile(os.path.split(self.image.name)[-1],
temp_handle.read(), content_type=DJANGO_TYPE)
self.thumbnail.save('%s_thumbnail.%s'%(os.path.splitext(suf.name)[0],FILE_EXTENSION), suf, save=False)
def save(self):
self.create_thumbnail()
super(ImageWithThumbnail, self).save()
现在我要将缩略图保存在documents/small/
中。但是在上传图像以创建缩略图时如何从视图或模型中调用此create_thumbnail
函数?
答案 0 :(得分:0)
你是不是想要在你的视图中调用该函数。 然后就可以了
from urappname.models import Document
并使用
致电Document.create_thumbnail()
答案 1 :(得分:0)
您可以通过覆盖django的默认save()方法来完成此操作。 为此,在模型类下定义此save()函数,如下所示:
def save(self, *args, **kwargs):
self.create_thumbnail()
super(Document, self).save(*args, **kwargs)