7👍
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)
1👍
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
- Autocommit Migration from Django 1.7 to 1.8
- Coerce in django forms
- Empty catalog when internationalizing JavaScript code
0👍
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)