1

Given this example taken from here:

def simple(request):
    import random

    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    from matplotlib.dates import DateFormatter

    fig=Figure()
    ax=fig.add_subplot(111)
    x=[]
    y=[]
    now=datetime.datetime.now()
    delta=datetime.timedelta(days=1)
    for i in range(10):
        x.append(now)
        now+=delta
        y.append(random.randint(0, 1000))
    ax.plot_date(x, y, '-')
    ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
    fig.autofmt_xdate()
    canvas=FigureCanvas(fig)
    response=django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

How can I write the view in such a way that uses a template and variable like: return render_to_response ('template.html',{'graph': <graph generated by matplotlib> }

1 Answer 1

2

When I had a similar situation, I used two views. One used matplotilb to generate a PNG, while the other used used django templates to create an HTML page that presented the PNG (and some other data). The param sent to the template was just the PNG filename. The other view is then attached to he appropriate .png URLs.

One problem is if you want to calculate some parameters which are used both for generating the HTML and PNG. I encoded such information in the filename. This is painful, and slightly hacky, but it's s also good for the user if all the info is in the filename when she saves it.

Sign up to request clarification or add additional context in comments.

3 Comments

I don't suppose you know of another library/package that will do this? Really want to avoid writing 2 views for each type of graph.
So you had to write each graph to the table and call it again?
I thought having two views was the natural thing to do, since there are two URLs involved. One for the PNG file and one for the HTML wrapping-page. It might be that you only want to serve up the PNG, without a wrapping page, but in this case I don't see how django templates come into it at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.