Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can embed pygal charts in django templates

I use pyGal for making charts, but I can't insert them in django templates. It works great, if I try like this in views.py

 return HttpResponse(chart.render())

But when I make something like this in my template in doesn't work at all

 {{chart.render}}
like image 558
vZ10 Avatar asked Jul 12 '13 06:07

vZ10


4 Answers

The tutorial on pygal is accurate, however the issue you are probably seeing is from flask escaping html by default. In your template add:

{{ graph|safe  }}

or

{{ graph.render()|safe  }}

Depending what you pass to the template.

This solved the issue for me.

like image 79
jpyth Avatar answered Oct 23 '22 22:10

jpyth


This is what I do (and it works swimmingly!):

views.py:

def myview(request):
    # do whatever you have to do with your view
    # customize and prepare your chart
    # save SVG chart to server
    mychart.render_to_file('/path/to/graph.svg') 
    # end your view. For instance:
    context = {'message': 'Hello Pygal!'}
    return render(request, 'path/to/mytemplate.html', context)

mytemplate.html:

<embed type="image/svg+xml" src="/path/to/graph.svg" width="90"/>

That is all!

like image 39
BringBackCommodore64 Avatar answered Oct 24 '22 00:10

BringBackCommodore64


I could write you the answer, but I believe that this tutorial will provide a more detailed explanation.

like image 2
Games Brainiac Avatar answered Oct 24 '22 00:10

Games Brainiac


multiple ways to do it

one way is

in temlate:

<div id="chart">
   <embed type="image/svg+xml" src= {{ chart|safe }} />
</div>

In django view :

return render(request, "temlate.html" , { 
    "chart": date_chart.render_data_uri()
})
like image 1
Saurabh Chandra Patel Avatar answered Oct 24 '22 00:10

Saurabh Chandra Patel