将变量传递给 Django 模板中的 Matplotlib

时间:2021-01-25 08:06:29

标签: python django matplotlib

我正在使用此代码在我的网站上创建一个 plot

views.py

def setPlt():
    x = ["07/01", "07/02", "07/03", "07/04", "07/05", "07/06", "07/07"]
    y = [3, 5, 0, 5, 6, 10, 2]
    plt.bar(x, y, color='#00d5ff')
    plt.title(r"$\bf{Repli Graph}$", color='#3407ba')
    plt.xlabel("Date")
    plt.ylabel("Number of Repli")


def plt2svg():
    buf = io.BytesIO()
    plt.savefig(buf, format='svg', bbox_inches='tight')
    s = buf.getvalue()
    buf.close()
    return s


def repli_plot(request):
    setPlt()  
    svg = plt2svg()
    plt.cla()
    response = HttpResponse(svg, content_type='image/svg+xml')
    return response

urls.py

path("Products/Repli/plot", views.repli_plot, name="media_power-plot")

在 html 中

<img src="{% url 'media_power-plot' %}" width=800 height=400>

我有一些虚拟值来创建图表。但我想知道如何传递带有 TemplateView 值的变量,我在生成图表的页面上使用。 我像这样在 values 中将 jinja 传递给 context

return render(request, self.template_name, self.context)

我想要 self.context 中的 plot

0 个答案:

没有答案
相关问题