[Django]-Saving a matplotlib graph as an image field in database

4👍

matplotlib.pyplot.savefig accepts file-like object as the first parameter. You can pass StringIO/BytesIO (according to your python version).

f = StringIO()
plt.savefig(f)

Then, use django.core.files.ContentFile to convert the string to django.core.files.File (because FieldFile.save accepts only accept an instance of django.core.files.File).

content_file = ContentFile(f.getvalue())
model_object = Model(....)
model_object.image_field.save('name_of_image', content_file)
model_object.save()

Leave a comment