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.
Asked
Active
Viewed 2,462 times
3

falsetru
- 357,413
- 63
- 732
- 636

Aswin Murugesh
- 10,831
- 10
- 40
- 69
1 Answers
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()

falsetru
- 357,413
- 63
- 732
- 636
-
Am using python 2.7 and I get a `not defined` error for both StringIO and BytesIO – Aswin Murugesh Dec 14 '13 at 06:16
-
1@AswinMurugesh, Import it. `from io import BytesIO` / `from StringIO import StringIO` / `from cStringIO import StringIO`. – falsetru Dec 14 '13 at 06:18
-
@AswinMurugesh, http://docs.python.org/2/library/stringio.html / http://docs.python.org/3/library/io.html#io.BytesIO – falsetru Dec 14 '13 at 06:19
-
what is `fig` actually? Is it a savefig object or a pyplot object? – Aswin Murugesh Dec 14 '13 at 06:20
-
@AswinMurugesh, an instance of [`matplotlib.pyplot`](http://matplotlib.org/api/pyplot_api.html#module-matplotlib.pyplot). I renamed `fig` to `plt` because `plt` is commonly used name. – falsetru Dec 14 '13 at 06:29
-
plt.save(f) gives me this error: `module' object has no attribute 'save'` – Aswin Murugesh Dec 14 '13 at 06:37
-
@AswinMurugesh, It is `savefig`. I misspelled it in the code. Sorry. – falsetru Dec 14 '13 at 06:43
-
The view works without errors. how do I check if it is saved correctly? – Aswin Murugesh Dec 14 '13 at 06:52
-
1@AswinMurugesh, Please read [Managing files | Django documentation](https://docs.djangoproject.com/en/dev/topics/files/) – falsetru Dec 14 '13 at 06:54
-
1[Here](http://stackoverflow.com/a/8598881/1308967) 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. – Chris Feb 06 '16 at 12:39