Integrating PyChart and Django

The Django documentation contains a lot of information. Some specialized types of output are described, like PDF's using ReportLab or CSV's using Pythons built-in CSV module.

If you only remember one thing about handling non-HTML output via Django: know that you can use the HttpResponse object as if it were a file. Writing to such an object and returning it will give you the output you wrote. It's a very simple concept, but one that translates well to third-party libraries.

One example is with PyChart, used to generate charts and plots of all kinds. Integrating PyChart and Django becomes easy. In your Django-view:

from django.http import HttpResponse

from pychart import *

def my_plot(request):
    response = HttpResponse(mimetype = 'image/png')
    can = canvas.init(response, format = "png")
    data = [("", 10, 50), ("", 20, 100), ("", 0, 100)]
    r = area.T(y_coord = category_coord.T(data, 0))
    chart_object.set_defaults(bar_plot.T, direction="horizontal", data=data)
    r.add_plot(bar_plot.T(label="test"))
    r.draw()
    can.close()
    return response

Above outputs something like this. Nothing fancy, but the PyChart site contains plenty of examples to spice up your Django-generated data. Again, the main point is to realize that canvas.init() accepts a File-object as its first argument, which in our case is our HttpResponse object.