Save Matplotlib plot image into Django model
There are several problems with your code:
You should not save the figure to a
StringIO
but instead, aio.BytesIO()
. This is because the contents of the PNG file isn't human-readable text but binary data.Another problem is how you handle the
BytesIO
(StringIO
in your code) when passing it tosavefig
. ABytesIO
isn't associated with a file (that's the whole point of having an in-memory file-like object), so it doesn't have a file name – which is what I suppose you want to get at by thatu'%s' % figure
expression. Instead, just write to the file-like object itself.Third, use a
django.core.files.images.ImageFile
instead ofContentFile
. Also, initialise it with theBytesIO
object itself, not its bytes value.
The relevant portion of your code then becomes:
figure = io.BytesIO()plt.plot(xvalues, yvalues)plt.savefig(figure, format="png")content_file = ImageFile(figure)
you might also want to try the plotly library - they have a js script that you can add to the html (https://plot.ly/javascript/getting-started/) and you can always serialize the arrays needing to be imported into the graph