Saving a decoded temporary image to Django Imagefield

Jharwood picture Jharwood · Feb 27, 2013 · Viewed 10.9k times · Source

I'm trying to save images which have been passed to me as Base64 encoded text into a Django Imagefield.

But it seems to not be saving correctly. The database reports all my images are stored as "" when it should report them as a filename for example:

"template_images/template_folders/myImage.png"

The code that's trying to save my images is as follows:

elif model_field.get_internal_type() == "ImageField" or model_field.get_internal_type() == "FileField":  # Convert files from base64 back to a file.
    if field_elt.text is not None:
        setattr(instance, model_field.name, File(b64decode(field_elt.text)))

Answer

dshap picture dshap · Mar 13, 2013

After reading this answer, I got this to work:

from base64 import b64decode
from django.core.files.base import ContentFile

image_data = b64decode(b64_text)
my_model_instance.cool_image_field = ContentFile(image_data, 'whatup.png')
my_model_instance.save()

Therefore, I suggest you change your code to:

from django.core.files.base import ContentFile

# Your other code...

elif model_field.get_internal_type() == "ImageField" or model_field.get_internal_type() == "FileField":  # Convert files from base64 back to a file.
    if field_elt.text is not None:
        image_data = b64decode(field_elt.text)
        setattr(instance, model_field.name, ContentFile(image_data, 'myImage.png'))

Then, assuming your ImageField is defined with the upload_to argument set to template_images/template_folders/, you should see the file save down to YOUR_MEDIA_URL/template_images/template_folders/myImage.png