【问题标题】:How I can embed pygal charts in django templates如何在 django 模板中嵌入 pygal 图表
【发布时间】:2013-07-10 15:29:35
【问题描述】:

我使用 pyGal 制作图表,但无法将它们插入 django 模板。 如果我在views.py中尝试这样,它会很好用

 return HttpResponse(chart.render())

但是当我在我的模板中做这样的事情时根本不起作用

 {{chart.render}}

【问题讨论】:

    标签: django django-templates pygal


    【解决方案1】:

    多种方法

    一种方法是

    在模板中:

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

    在 django 视图中:

    return render(request, "temlate.html" , { 
        "chart": date_chart.render_data_uri()
    })
    

    【讨论】:

      【解决方案2】:

      我可以给你写答案,但我相信this教程会提供更详细的解释。

      【讨论】:

      • 这个教程我已经读了好几遍了,但是没有用。也许我是问题))
      【解决方案3】:

      这就是我所做的(而且效果很好!):

      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"/>
      

      就是这样!

      【讨论】:

        【解决方案4】:

        关于 pygal 的教程是准确的,但是您可能看到的问题是烧瓶默认转义 html。在您的模板中添加:

        {{ graph|safe  }}
        

        {{ graph.render()|safe  }}
        

        取决于您传递给模板的内容。

        这为我解决了这个问题。

        【讨论】:

          猜你喜欢
          • 2016-08-19
          • 2023-03-02
          • 1970-01-01
          • 1970-01-01
          • 2015-09-22
          • 2017-04-05
          • 2013-05-26
          • 2017-11-06
          • 2010-09-20
          相关资源
          最近更新 更多