I'm developing an project in Django and I have a view that generate a chart as am image and returns it to me as a web page into a HttpResponse(). And it already works, but that´s the thing, I need to put some more information on the page and buttons...
So how can I return this image in a render_to_response()? Because in this I can tell which template use and place my stuff there. Or how can I place html stuff on the HttpResponse() with the image?
Here it is my code that I want to transform in a render_to_response(), it's a function that generate a multiple line chart:
def chart(request):
if 'checks[]' in request.GET and request.GET['checks[]']:
#getting id's of selected tags
chosen = request.GET.getlist('checks[]')
tags = Tag.objects.filter(id__in = chosen)
fig=Figure()
ax=fig.add_subplot(111)
strIdTags = ""
#getting all values of all selected tags
for tag in tags:
if Values.objects.filter(tag = tag.id).count > 0:
#values of one tag
values = Values.objects.filter(tag = tag.id)
strIdTags+=str(tag.id)
strIdTags+="; "
x = []
y = []
#all values of one tag
for value in values:
y.append(value.value)
x.append(value.datetime)
#ax.plot_date(value.value, value.datetime, '-')
ax.plot_date(x, y, '-')
ax.annotate("Tag "+str(tag.id), (x[0],y[0]),
arrowprops=dict(facecolor='black', shrink=0.05))
ax.xaxis.set_major_formatter(DateFormatter('%d/%m/%Y - %H:%M:%S'))
ax.set_title("Values of Tags: "+strIdTags)
ax.set_xlabel("Date-Time")
ax.set_ylabel("Values")
fig.autofmt_xdate()
canvas=FigureCanvas(fig)
response=HttpResponse(content_type='image/png')
canvas.print_png(response)
return response
You need a different view instead, that returns a rendered template:
def chart_view(request):
return render(request, 'templates/chart_template.html')
In that template, define all the HTML you need, including an <img>
tag with a link to the view that you've defined in your original post that returns the image:
<html>
...etc...
<img src='{% url 'chart' %}?checks=...' />
The HTML template will be returned to the user as an HTML page (complete with all the buttons etc you want), and the chart image will be embedded in it just like any other image.