vZ10
vZ10

Reputation: 2676

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}}

Upvotes: 5

Views: 3765

Answers (4)

Saurabh Chandra Patel
Saurabh Chandra Patel

Reputation: 13586

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()
})

Upvotes: 1

Nafiul Islam
Nafiul Islam

Reputation: 82440

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

Upvotes: 2

BringBackCommodore64
BringBackCommodore64

Reputation: 5460

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!

Upvotes: 4

jpyth
jpyth

Reputation: 76

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.

Upvotes: 6

Related Questions