pythondjangobase64

"TypeError: can not serialize 'ContentFile' object"


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


file = "data:image/png;base64,iVBORw0KGgoAAAANSUhEU..."
format, imgstr = file.split(';base64,') 
ext = format.split('/')[-1] 

data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext)
somemodel.save(data)

I want to save a base64 media file in a Django model file field.

I expected it to save the data, but I got:

TypeError: 'Cannot serialize 'ContentFile' object'.

Can someone please tell me where I went wrong?


Solution

  • Django can't serialize ContentFile objects directly. Write the ContentFile to a temporary file and then save that file to the model's field:

    import base64
    import uuid
    from django.core.files.base import ContentFile
    from django.core.files.storage import default_storage
    
    file = "data:image/png;base64,iVBORw0KGgoAAAANSUhEU..."
    format, imgstr = file.split(';base64,')
    ext = format.split('/')[-1]
    data = ContentFile(base64.b64decode(imgstr))
    file_name = '{}.{}'.format(uuid.uuid4(), ext)
    path = default_storage.save('tmp/' + file_name, data)
    somemodel.filefield = path
    somemodel.save()