embedding generated img inside django template

前端 未结 3 1650
囚心锁ツ
囚心锁ツ 2021-01-05 18:28

how would I embedded generated image inside django template?

something like

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


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-05 19:24

    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

    embedded
    

    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.

提交回复
热议问题