2013-02-22 81 views
0

代碼是這樣的:問題在Django創建縮略圖

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

您是否意味着您想在視圖中調用該函數。 然後,你可以做

from urappname.models import Document 

,並通過覆蓋默認保存的Django()方法調用使用

Document.create_thumbnail() 
+0

其實我想動態創建縮略圖,同時上傳。在我保存在數據庫中的數據我認爲頁圖像中像這樣:newdoc = Document(docfile = request.FILES ['docfile'],thumbnail = request.FILES ['docfile'])\t newdoc.save() – curiousguy 2013-02-22 09:46:14

0

你可以做到這一點。 爲此,定義這個模型類下保存()函數如下:

def save(self, *args, **kwargs): 
    self.create_thumbnail() 
    super(Document, self).save(*args, **kwargs)