Generating dynamic charts with Matplotlib in Djang

2020-07-30 07:55发布

问题:

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 View

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

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?

I hope that was clear!

回答1:

You can access your chart view in your template using the url-templatetag with the appropiate parameters.

So it should look like:

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

Or, as you are using get-parameters:

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


回答2:

have been doing this for years (works with pySVG generated SVG graphs as well btw) , however recently I encountered many problems with installing matplotlib in virtualenvs.

I resorted to adding the system wide matplotlib libraries (from the ubuntu repositories) to the virtualenvs instead of the usual pip install .... anthem