Converting bytes to file in Django / Python

Question:

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

print(myPDF)
> b'%PDF-1.3n1 0 objn<<n/Type /Pagesn/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.

Asked By: bones225

||

Answers:

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

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

obj.document = ContentFile(myPDF, '........pdf')
obj.save()
Answered By: bones225
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.