Reputation: 2905
When a user clicks the upload button to upload their csv my website should return a matplotlib plot. I have the plot saved to a buffer and it now just needs to display in the same page as where the upload button is.
I am a beginner to Django so the following is what I did (warning: some pseudocode ahead)
In views.py and yes I can see that the httprequest
returned by plotResult(request, csvfile_path)
doesn't interact with list.html
. I'm not sure how to get it to
def list(request):
#Working code for uploading a csv and retrieving the path to the uploaded file
if document uploaded:
return plotResult(request, csvfile_path)
return render(
request,
'list.html',
{'documents': documents, 'form': form}
)
def plotResult(request, sorted_dir):
# Bunch of code for computing the plot - functions in custom_script.py
return Plot_Composite_metrics(bunch of parameters)
Plot_Composite_metrics is in custom_script.py which is in the same directory as views.py and contains many functions for computing the plot:
def Plot_Composite_metrics(bunch of parameters):
# More code for computing the plot
ax = plt.subplot2grid((3,4), (0,0), colspan=4)
# Code for adding attributes to ax.
# Store the now built image in a string buffer
buffer = StringIO.StringIO()
canvas = pylab.get_current_fig_manager().canvas
canvas.draw()
pilImage = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb())
pilImage.save(buffer, "PNG")
pylab.cose()
return HttpResponse(buffer.getvalue(), mimetype="image/png")
in list.html I have what I need to generate the upload functionality, the following to produce the matplotlib plot:
<img src="data:image/png;base64,{{graphic|safe}}">
When I run this there is no crash, the img tag above at first only has its empty filler. Then after uploading the website returns the plot, but on a page of its own instead of at the img tag below the upload button. How do I make it so that the matplotlib plot appears embedded on the same page?
If by any chance knowing what the plot looks like is important, here:
Upvotes: 2
Views: 2074
Reputation: 6214
I have saved my plots in SVG format for similar purpose,
import six
fig = plt.figure()
# plot some data
tmp = six.StringIO()
fig.savefig(tmp, format='svg', bbox_inches='tight')
template = loader.get_template('path_to_/template.html')
c = Context({ 'svg': tmp.getvalue() })
return HttpResponse(template.render(c))
In the template file,
{% if svg %}
<div style="width:60em;height:46em">
{% autoescape off %}
{{ svg }}
{% endautoescape %}
</div>
Upvotes: 2