使用Django中的Matplotlib生成动态图表

时间:2011-04-14 09:04:00

标签: django httpwebrequest matplotlib

所以我有2个视图:第一个视图根据请求生成html,第二个视图生成要显示第一个视图的图表。

HTML查看

def activation_signupcount(request):

    if 'datestart' not in request.GET:

        return render_to_response('activation/activation_signupcount.html', {'datestart':''})

    else:

        datestart = request.GET['datestart']
        dateend = request.GET['dateend']

        return render_to_response('activation/activation_signupcount.html', {'datestart':datestart, 'dateend':dateend})#

CHART VIEW

def activation_signupcount_graph(request):

    datestart = request.GET['datestart'] #this doesnt work
    dateend = request.GET['dateend'] #this doesnt work

    print datestart,dateend

    # open sql connection
    cursor = connection.cursor()
    # execute query
    cursor.execute("SELECT COUNT(1), JoinDate FROM users WHERE JoinDate BETWEEN '"+ datestart +"' AND '"+ dateend +"' GROUP BY JoinDate;")
    # close connection

    data = cursor.fetchall()

    cursor.close()
    connection.close() 

    fig = Figure()
        ax = fig.add_subplot(111)

    x = []
    y = []

    x = [k[1] for k in data]
    y = [k[0] for k in data]

    ax.plot_date(x, y, '-')
    ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
    fig.autofmt_xdate()
    canvas = FigureCanvas(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)

    return response

所以在页面activation/activation_signupcount.html上,我有2个日期字段,start和end,它们提交GET请求。所以我的问题是,如何将这两个日期变量解析为我的函数activation_signupcount_graph以获取生成图表的开始/结束日期?

我希望这很清楚!

2 个答案:

答案 0 :(得分:3)

您可以使用带有适当参数的url-templatetag访问模板中的图表视图。

所以看起来应该是这样的:

<img src="{% url yourapp.chart_view start_date end_date %}" />

或者,正如您使用的是get-parameters:

<img src="{% url yourapp.chart_view %}?datestart={{ datestart }}" />

答案 1 :(得分:0)

多年来一直这样做(使用pySVG生成的SVG图表以及btw),但是最近我在virtualenvs中遇到了很多安装matplotlib的问题。

我使用系统范围的matplotlib库(从ubuntu存储库)添加到virtualenvs而不是通常的pip install .... anthem