2011-04-06 43 views
7

我试图从StringIO(或cStringIO,更具体地说)获取数据并将其转换为django.core.files.images.ImageFile。将StringIO对象转换为Django ImageFile

但它不起作用。所有这一切,我的意思是它以多种方式失败,而谷歌已经让我失败了。

到目前为止我有:

pi = ProductImage(product=product) 
image = ImageFile(image_file) 
image.name = image_name # defined elsewhere 
pi.source_image.save(image_name, image) 
pi.save() 

我的堆栈跟踪是这样的:

File "dev.py", line 359, in process_csv_item 
    pi.source_image.save(image_name, image) 
File "C:\Python26\lib\site-packages\django\db\models\fields\files.py", line 92, in save 
    self.name = self.storage.save(name, content) 
File "C:\Python26\lib\site-packages\django\core\files\storage.py", line 48, in save 
    name = self._save(name, content) 
File "C:\Python26\lib\site-packages\django\core\files\storage.py", line 168, in _save 
    for chunk in content.chunks(): 
File "C:\Python26\lib\site-packages\django\core\files\base.py", line 65, in chunks 
    counter = self.size 
File "C:\Python26\lib\site-packages\django\core\files\base.py", line 39, in _get_size 
    elif os.path.exists(self.file.name): 
AttributeError: 'cStringIO.StringI' object has no attribute 'name' 

我在哪里可以看未来?

回答

15

使用django.core.files.base.ContentFile(IMAGE_FILE):

pi = ProductImage(product=product) 
pi.source_image.save(image_name, ContentFile(image_file.read())) 
pi.save() 
+1

关闭,它结束了:'pi.source_image.save(IMAGE_NAME,ContentFile(image_file.read()))' – 2011-04-06 21:24:25

+0

不适用于我。该模型已成功保存,但在渲染Django时抛出错误“IOError:无法识别图像文件” – 2014-01-31 12:46:30

+1

也许您在PIL中缺少对格式类型的支持。如果您仍有问题,请尝试询问完整的问题。 – gcbirzan 2014-02-05 15:56:05