Embedding generated img inside django template

how would i embed the generated image inside the django template?

sort of

return render_to_response('graph.html', { 'img': get_graph() })

I do not want this - because it just sends the image

http.HttpResponse(get_graph(), mimetype="image/png")
+5
source share
3 answers

You can base64 encode image data and use data URIs .

+4
source

You can map the URL to one of your view functions, which returns an HttpResponse with image data and uses that URL as src for your element <img>, for example.

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"/>
+3
source

matplotlib django, django ( , ).

<img alt="embedded" src="data:image/png;base64,{{inline_png}}"/>

:

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 is that it does not work in IE7 or IE8 - it works with IE9 and newer, thought and, of course, with all standard web browsers.

+3
source

All Articles