动态创建ImageField Django

时间:2012-03-08 17:46:08

标签: python django imagemagick django-models

我有一个模型,我想通过ImageMagick创建一个缩略图(是的,使用行命令),它可以工作,但是我无法将我在模型MedicoImage中创建的图像与“mini”字段相关联。

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()

1 个答案:

答案 0 :(得分:1)

只需使用:

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

我认为应该这样做。