Show dynamically generated image in template

Hi,

I am struggling to pass a dynamically generated image (not in a file) to an HTML-template to show it.

Basically I have an object containing an image (coming from matplotlib) and I managed to pass it to HTML directly in django using the following code:

from django.http import HttpResponse

def  sample_view(request):
    # ...
    # image object ist contained in canvas
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

However, I would like to replace this by code that sends the image directly to an HTML-template. I tried the following

from django.http import HttpResponse

def  sample_view(request):
    # ...
    # image object ist contained in canvas
    template = loader.get_template('sample_view.html')
    context = {
        'canvas': canvas,
    }
    response =  HttpResponse(template.render(context, request))
    return response

Where the template is just
<img src="{{ canvas }}" />

Unfortunately, this code doesn’t work. Is there a way to achieve the same behaviour without saving the images to a file first?

Thanks in advance!

You could try including the image in a data: URL, perhaps?

Hm. I tried that, but somehow I couldn’t get it to work. At the end I saved the file to the disk and statically loaded it.