4

我是 Django 的新手。我试图通过 HTML(graph.html) 加载图像。views.py 包括

def avg_duration_vs_time_of_day(request):
    figName="figGraph.png"
    path="Telecom/Images/"+figName
    day = [1, 2, 3, 4]
    query = "select time_of_day,avg(duration) from fact_table group by time_of_day"
    avg_call_day = connect(query)
    import matplotlib.pyplot as plt
    plt.figure(figsize = (4,4))
    plt.xlabel("Time of Day",fontdict={'fontsize':8})
    plt.ylabel("Average Call Duration in seconds",fontdict={'fontsize':8}) 
    plt.title("Average Call Versus Time of Day",fontdict = {'fontsize':8})
    plt.plot(day,avg_call_day,color='green', linestyle='solid',linewidth=1, marker='o',markerfacecolor='blue', markersize=0)
    plt.bar(day,avg_call_day,width=0.2,align='center')
    plt.savefig(path)
    image_data = open(path, "rb").read()
    context = { 'image_data': image_data }    
    return render_to_response('welcome/graph.html', context)

graph.html 包括

<div>
<img src="{% 'views.avg_duration_vs_time_of_day.image_data' %} " />
</div>

但图像无法在浏览器中加载,错误是

TemplateSyntaxError at /graph/
Invalid block tag: ''views.avg_duration_vs_time_of_day.image_data''

解决办法是什么 ?

4

1 回答 1

2

您应该将图像路径放在模板上下文中,而不是图像本身:

context = { 'image_path': path }    
return render_to_response('welcome/graph.html', context)

而且,您的模板语法不正确:

<div>
<img src="{{ image_path }}"/>
</div>

希望您的设置配置正确。仅供参考,请参阅:

希望有帮助。

于 2013-07-03T12:35:01.877 回答