7

I'm trying to take data from a StringIO (or cStringIO, more specifically) and convert it to a django.core.files.images.ImageFile.

But it doesn't work. Any by that, I mean that it fails in a multitude of ways, and Google has failed me.

So far I've got:

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

My stack trace goes something like this:

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'

Where can I look next?

Brian Hicks
  • 6,213
  • 8
  • 51
  • 77

1 Answers1

16

Use django.core.files.base.ContentFile(image_file):

pi = ProductImage(product=product)
pi.source_image.save(image_name, ContentFile(image_file.read()))
pi.save()
gcbirzan
  • 1,494
  • 11
  • 17
  • 1
    Close, it ended up being: `pi.source_image.save(image_name, ContentFile(image_file.read()))` – Brian Hicks Apr 06 '11 at 21:24
  • Does not work for me. The model is saved successfully, but on rendering Django throws error `IOError: cannot identify image file` – Petr Peller Jan 31 '14 at 12:46
  • 1
    Maybe you're missing support in PIL for the format type. Try asking a full question about it, if you still have a problem. – gcbirzan Feb 05 '14 at 15:56