在Django中用Matplotlib生成动态图表

在Django中用Matplotlib生成动态图表

本文介绍了在Django中用Matplotlib生成动态图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I have 2 views: the first one generates the html on request, the second view generates the chart to display for the first view.

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

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

So on the page activation/activation_signupcount.html, I have 2 date fields, start and end, which submits a GET request. So my question is, how can I parse these 2 date variables to my function activation_signupcount_graph to get the start/end dates to generate the chart?

我希望这是清楚的!

推荐答案

您可以使用 url-templatetag 。

所以应该看起来像:

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

或者,正如使用get-parameters:

Or, as you are using get-parameters:

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

这篇关于在Django中用Matplotlib生成动态图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 20:58