[Solved]-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, a io.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 to savefig. A BytesIO 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 that u'%s' % figure expression. Instead, just write to the file-like object itself.

  • Third, use a django.core.files.images.ImageFile instead of ContentFile. Also, initialise it with the BytesIO 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



Working version:

import io
from django.core.files.base import ContentFile

figure = io.BytesIO()
plt.savefig(figure, format='png')
content_file = ContentFile(figure.getvalue())
one_round.chart.save('chart.png', content_file)

Leave a comment