【问题标题】:Converting a StringIO object to a Django ImageFile将 StringIO 对象转换为 Django ImageFile
【发布时间】:2011-07-31 03:46:24
【问题描述】:

我正在尝试从 StringIO(或者更具体地说是 cStringIO)获取数据并将其转换为 django.core.files.images.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'

接下来我可以看哪里?

【问题讨论】:

    标签: python django stringio


    【解决方案1】:

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

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

    【讨论】:

    • 关闭,结果是:pi.source_image.save(image_name, ContentFile(image_file.read()))
    • 对我不起作用。模型保存成功,但在渲染 Django 时抛出错误IOError: cannot identify image file
    • 也许您在 PIL 中缺少对格式类型的支持。如果您仍有问题,请尝试提出完整的问题。
    猜你喜欢
    • 2019-01-18
    • 2014-09-15
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    • 2011-03-14
    • 2013-09-19
    • 2021-06-18
    相关资源
    最近更新 更多