0

代码是这样的:

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但是在上传图片创建缩略图时,如何从视图或模型中调用这个函数呢?

4

2 回答 2

0

您可以通过覆盖 django 的默认 save() 方法来做到这一点。为此,请在您的模型类下定义此 save() 函数,如下所示:

def save(self, *args, **kwargs):
    self.create_thumbnail()
    super(Document, self).save(*args, **kwargs)
于 2013-12-19T06:05:51.757 回答
0

你的意思是你想在你的视图中调用这个函数。然后你可以做

from urappname.models import Document

并使用

Document.create_thumbnail()
于 2013-02-22T09:39:04.390 回答