2012-03-08 71 views
1

我有一個模型,我想通過ImageMagick創建一個縮略圖(是與線命令),它的工作原理,但我不能將創建的圖像與我的模型MedicoImage中的字段「迷你」相關聯。動態創建ImageField Django

class MedicoImage(models.Model): 
    medico   = models.ForeignKey(Medico) 
    imagem   = models.ImageField(max_length=300,upload_to='img_medico') 
    mini   = models.ImageField(max_length=300,upload_to='img_medico/mini',verbose_name=u'Miniatura',null=True, blank=True) 


def save(self, *args, **kwargs): 
    super(MedicoImage, self).save(*args, **kwargs) 
    if not self.mini: 
     path_destino = os.path.dirname(self.imagem.path) + '/mini/' 
     path_destino += os.path.basename(self.imagem.path).partition('.')[0] + '_mini' + '.png' 
     comando = 'convert ' + self.imagem.path + ' -resize 30% ' + path_destino 
     if subprocess.call(comando,shell=True) == 0: 
      f = File(open(path_destino,'r')) 
      self.mini(path_destino, f.read()) 
      self.mini.save() 
      print 'Thumbnail created!' 

這裏有什麼問題?

  f = File(open(path_destino,'r')) 
      self.mini(path_destino, f.read()) 
      self.mini.save() 
+0

您是否使用'django.core.files'中的'File'? – aganders3 2012-03-08 17:55:51

+0

是的,我正在導入 from django.core.files import文件 – rayashi 2012-03-08 18:02:04

回答

1

只需使用:

f = File(open(path_destino,'r')) 
self.mini.save(path_destino, f, True) 

我認爲應該這樣做。

+0

謝謝!有用! – rayashi 2012-03-08 18:08:31