Error in Django when using matplotlib examples Error in Django when using matplotlib examples django django

Error in Django when using matplotlib examples


At the moment, matplotlib's writing functions require the seek ducktype to use the response at a file. You can write to a buffer, like this:

import iodef mplimage(request):    f = matplotlib.figure.Figure()    # Code that sets up figure goes here; in the question, that's ...    FigureCanvasAgg(f)    buf = io.BytesIO()    plt.savefig(buf, format='png')    plt.close(f)    response = HttpResponse(buf.getvalue(), content_type='image/png')    return response


You can just replace the response with a buffer and then add the buffer to the response. This will give an appropriate object to canvas.print_png() and keep code changes to a minimum.

def mplimage(request):    f = matplotlib.figure.Figure()    buf = io.BytesIO()    canvas = FigureCanvasAgg(f)    canvas.print_png(buf)    response=HttpResponse(buf.getvalue(),content_type='image/png')    # if required clear the figure for reuse     f.clear()    # I recommend to add Content-Length for Django    response['Content-Length'] = str(len(response.content))    #    return response