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
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()
10 Comments
Aswin Murugesh
Am using python 2.7 and I get a
not defined error for both StringIO and BytesIOfalsetru
@AswinMurugesh, Import it.
from io import BytesIO / from StringIO import StringIO / from cStringIO import StringIO.falsetru
falsetru
@AswinMurugesh, Please read Managing files | Django documentation
|