django-content-gallery
                                
                                 django-content-gallery copied to clipboard
                                
                                    django-content-gallery copied to clipboard
                            
                            
                            
                        How to upload an image from memory
I'm trying to add an image that has been extracted from an email straight into django content gallery and tried various approaches with no success. The payload is a bytes object. Would you know how to do this, or how to manually upload a file if I first put the payload into a temporary file?
This::
filename = metadata['filename']
pre, ext = os.path.splitext(filename)
content_type = None
if ext == '.jpg' or ext == '.jpeg':
    content_type = 'jpeg'
elif ext == '.png':
    content_type = 'png'
# load into memory to suit django-content-gallery
image = InMemoryUploadedFile(payload, None, filename,
                                  content_type, sys.getsizeof(payload), None)
image = ImageModel(image=image, content_object=obj)
image.save()
Results in:
File "/Users/pbright/.virtualenvs/iofh1/lib/python3.6/site-packages/content_gallery/utils.py", line 123, in image_resize
  with Image.open(src) as img:
File "/Users/pbright/.virtualenvs/iofh1/lib/python3.6/site-packages/PIL/Image.py", line 2549, in open
  fp = io.BytesIO(fp.read())
File "/Users/pbright/.virtualenvs/iofh1/lib/python3.6/site-packages/django/core/files/utils.py", line 16, in <lambda>
  read = property(lambda self: self.file.read)
File "/Users/pbright/.virtualenvs/iofh1/lib/python3.6/site-packages/django/core/files/utils.py", line 16, in <lambda>
  read = property(lambda self: self.file.read)
 AttributeError: 'bytes' object has no attribute 'read'
This::
with tempfile.NamedTemporaryFile('wb', delete=False, suffix='.jpg') as f:
    f.write(payload)
    f.seek(0)
    image_name = os.path.basename(metadata_dict['filename'])
    img = ImageModel(content_object=obj)
    img.image.save(image_name, File(f), save=True)
    img.save()
gives::
    img.image.save(image_name, File(f), save=True)
   File "/Users/pbright/.virtualenvs/iofh1/lib/python3.6/site-packages/content_gallery/fields.py", line 88, in save
   name = self.image_data.data.name
  AttributeError: 'NoneType' object has no attribute 'name'