how would I embedded generated image inside django template?
something like
return render_to_response(\'graph.html\', { \'img\': get_graph() })
You can base64-encode the image data and use a data URI.
I wanted to embed a generated matplotlib image in a django page without making two trips to the django server (one to get the template, one to generate the image). I put the following in my template for the image
<img alt="embedded" src="data:image/png;base64,{{inline_png}}"/>
Then in the view method:
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import cStringIO as StringIO
import base64
num_signed_off = random.randint(0, 10)
num_reviewed = random.randint(0, 50)
num_unreviewed = random.randint(0, 50)
fig = Figure()
ax = fig.add_subplot(111, aspect='equal', axis_bgcolor='b')
ax.pie([num_signed_off, num_reviewed, num_unreviewed],
labels=['Signed Off', 'Reviewed', 'Unreviewed'],
colors=['b', 'r', 'g'],
)
ax.set_title('My Overall Stats')
ax.set_axis_bgcolor('r')
canvas=FigureCanvas(fig)
outstr = StringIO.StringIO()
canvas.print_png(outstr)
ret['inline_png'] = base64.b64encode(outstr.getvalue())
outstr.close()
return render(request, "my_view.html", ret)
The only problem with this is that it doesn't work in IE7 or IE8 - it works with IE9 and newer, thought, and of course with all the standards-based web browsers.
You can map a URL to one of your view functions that returns an HttpResponse with image data and use this URL as the src for your <img>
element e.g.
urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^image/', 'views.get_image'),
)
views.py
from django.http import HttpResponse
def get_image(request):
image_data = get_graph() # assuming this returns PNG data
return HttpResponse(image_data, mimetype="image/png")
index.html
<img src="image"/>