django: serve dynamic (reportlab) png to template

2020-03-24 11:14发布

问题:

I've spent the day on this issue with no success so help would be appreciated.

I generate a graph using reportlab and successfully render it to the browser using this tutorial:

        d = MyBarChartDrawing()

        #extract the request params of interest.
        #I suggest having a default for everything.
        if 'height' in request:
            d.height = int(request['height'])
        if 'width' in request:
            d.width = int(request['width'])

        if 'numbers' in request:
            strNumbers = request['numbers']
            numbers = map(int, strNumbers.split(','))    
            d.chart.data = [numbers]   #bar charts take a list-of-lists for data

        if 'title' in request:
            d.title.text = request['title']


        #get a GIF (or PNG, JPG, or whatever)
        binaryStuff = d.asString('png')

        return HttpResponse(binaryStuff, 'image/png')

My issue though is that I'd like to render this png within a template, like so (does not work):

return render(request, "subscription/monitorSizes.html", {'form':form,'message':'','graph':binaryStuff})

I've been hacking away at this issue for ages. It's no doubt a newbie problem! To save my sanity, would appreciate advice on this. Many thanks :)

edit: I found another stackoverflow Q on the same issue but it was not really solved.

回答1:

In views.py

def show_image(request):
    d = MyBarChartDrawing()
    #extract the request params of interest.
    #I suggest having a default for everything.
    if 'height' in request:
        d.height = int(request['height'])
    if 'width' in request:
        d.width = int(request['width'])

    if 'numbers' in request:
        strNumbers = request['numbers']
        numbers = map(int, strNumbers.split(','))    
        d.chart.data = [numbers]   #bar charts take a list-of-lists for data

    if 'title' in request:
        d.title.text = request['title']


    #get a GIF (or PNG, JPG, or whatever)
    binaryStuff = d.asString('png')

    return HttpResponse(binaryStuff, 'image/png')

def somepage(request):
     return render(request, "subscription/monitorSizes.html", {'form':form,'message':'','graph':reverse('show_image')})

In urls.py

...
url(r'^show_image/$', 'your_view.show_image', name='show_image'),
url(r'^somepage/$', 'your_view.somepage', name='somepage'),
...

In subscription/monitorSizes.html

...
{% if graph != '' %} <img src="{{ graph }}" alt="some_text"> {% endif %}
...