Search code examples
pythondjangobytesio

Converting bytes to file in Django / Python


In my Django app, I have a PDF in bytes:

print(myPDF)
> b'%PDF-1.3\n1 0 obj\n<<\n/Type /Pages\n/Count 2....

I want to save it in my database:

obj.document = myPDF
obj.save()

However I keep getting an 'bytes' object has no attribute '_committed' error on save.


Solution

  • The answer was a built-in Django function, ContentFile.

    from django.core.files.base import ContentFile
    ...
    
    obj.document = ContentFile(myPDF, '........pdf')
    obj.save()