Saving a matplotlib graph as an image field in database

2.5k views Asked by At

I just started learning matplotlib and I want to use it in one of my django apps. So I wanted to know how I can save the graph generated in an image field of my models, so that I can retrive whenever needed.

1

There are 1 answers

10
falsetru On BEST ANSWER

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()