3

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 Answer 1

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()
Sign up to request clarification or add additional context in comments.

10 Comments

Am using python 2.7 and I get a not defined error for both StringIO and BytesIO
@AswinMurugesh, Import it. from io import BytesIO / from StringIO import StringIO / from cStringIO import StringIO.
@AswinMurugesh, Please read Managing files | Django documentation
Here it says: For Python2.6 or better, use io.BytesIO instead of cStringIO.StringIO for forward-compatibility. In Python3, the cStringIO, StringIO modules are gone. Their functionality is all in the io module.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.