Search code examples
pythonajaxdjangoimage

Serve a dynamically generated image with Django


How do I serve a dynamically generated image in Django?

I have an html tag

<html>
...
    <img src="images/dynamic_chart.png" />
...
</html>

linked up to this request handler, which creates an in-memory image

def chart(request):
    img = Image.new("RGB", (300,300), "#FFFFFF")
    data = [(i,randint(100,200)) for i in range(0,300,10)]
    draw = ImageDraw.Draw(img)
    draw.polygon(data, fill="#000000")
    # now what?
    return HttpResponse(output)

I also plan to change the requests to AJAX, and add some sort of caching mechanism, but my understanding is that wouldn't affect this part of the solution.


Solution

  • I assume you're using PIL (Python Imaging Library). You need to replace your last line with (for example, if you want to serve a PNG image):

    response = HttpResponse(mimetype="image/png")
    img.save(response, "PNG")
    return response
    

    See here for more information.