3

I would like to take python generated matplotlib images and embed them into an HTML page that is generated by django. I am relatively new to django and have been struggling to get this to work. I can successfully generate a matplotlib image alone on a webpage but have been unable to embed into an HTML page. Django makes sense as my application will have many users that will have custom views with different data and frequently changing data coming from a database. I would like to avoid creating many static files.

I have looked at several posts but I am clearly missing something. For example: Generating dynamic charts with Matplotlib in Django, images on django site from matplotlib and Dynamically serving a matplotlib image to the web using python.

I generate my matplotlib image view with temp and I think the wrapper is detail. detail does not seem to work. The filename plotdata.py and under the django tutorial example polls

from datetime import datetime, time
from django.http import HttpResponse
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from django.contrib.auth.decorators import login_required
from django.shortcuts import render

@login_required()
def temp(request,x_id):

    #... code to generate fig for ploting - works well

    #This works but does not seem to pass file to HTML
    canvas = FigureCanvas(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

@login_required()
def detail(request, x_id):
    render(request, 'polls/plotdata.html', {'x_id': x_id})

My urls.py is as follows. temp works fine

from django.conf.urls import patterns, url
from django.views.generic import DetailView, ListView
from polls.models import Poll
from polls import plotdata

urlpatterns = patterns('',
    #polls url chopped out for brevity - follows tutorial
    url(r'^(?P<x_id>\d+)/plotdata/temp.png$', plotdata.temp, name='temp'),
    url(r'^(?P<x_id>\d+)/plotdata/detail$', plotdata.detail, name='detail'),
)

My plotdata.html is as follows

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}Plotting Template{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}
        <img src="{% url 'temp' x_id %}" >
        {% endblock %}
    </div>
</body>
</html>

The error generated is as follows.

NoReverseMatch at /polls/1303070002/plotdata/detail
Reverse for 'temp' with arguments '('1303070002',)' and keyword arguments '{}' not found.

This probably not the only problem with the above. I am certain I have missed something critical.

I tried hardcoding, as a test, to

<img src="/polls/1303070002/plotdata/temp.png" >

but it generated the following error

ValueError at /polls/1303070002/plotdata/detail
The view polls.plotdata.detail didn't return an HttpResponse object.

I would like to get this framework working so I can put text and buttons around the data plot. I am open to other ways to more efficiently create a solution. Thank you very much for helping out!

Repaired code, plotadata.py, is as follows

    #same header information from above before this line        
    canvas = FigureCanvas(fig)      #This needs to remain for savefig or print_png command
    response = HttpResponse(content_type='image/png')
    fig.savefig(response, format='png')     #Produces all white background
    return response

def detail(request, salesorder_id):
    return render(request, 'rsa/plotdata.html', {'x_id':x_id})

I included return before render this time... Changed path to hmtl file to avoid confusion with polls app. Using savefig versus print_png as it formats more generically. urls.py is the same. I am trying to get plotdata.html to work as above, passing a variable to url via {{ x_id }} but I am missing something. Same error as above, NoReverseMatch. If I replace, in plotdata.html

<img src="{% url 'temp' x_id %}" >

with

{% load staticfiles %}
<img src="{% static '/rsa/1303070001/plotdata/temp.png' %}" >

the image is embedded as desired. Now adding a dynamic path such as

<img src="{% static '/rsa/{{ x_id }}/plotdata/temp.png' %}" >

just escapes the literal x_id => /rsa/%7B%7B%20x_id%20%7D%7D/plotdata/temp.png. Trying x_id|safe ends up escaping the pipe and including literal safe... %7B%7B%20x_id%7Csafe%20%7D%7D. Hence I am trying to go back to using url versus static. Seems cleaner. I think there is something wrong with the variable I am passing, x_id

6
  • Try using static files for your image. {% static '<relative path goes here>' %} May 29, 2013 at 18:20
  • Thanks for the tip. Tried <img src="{% static '/polls/1303070002/plotdata/temp.png' %}" >. It resulted with the same didn't return an HttpResponse object error. It seems as though I may need to put image in a cStringIO buffer. May 30, 2013 at 0:18
  • in the detail view, add in a 'return' before the render function. That should do the trick May 30, 2013 at 14:20
  • Thanks again @GamesBrainiac. The forgotten render did the trick for the hardcoded case using the static call. The hardcoded path to the image is embedded in an html page. Unfortunately I can not seem to get variable path such as <img src="{% static '/polls/{{ x_id }}/plotdata/temp.png' %}" > working. This is why I selected url versus static. It gives dynamic addressing driven by a variable. with the return fix and original url code, I still get the same error. I am uncertain how the x_id variable is passed to the html to form the url May 31, 2013 at 1:35
  • 1
    {% static '/rsa/{{ x_id }}/plotdata/temp.png' %} should be {% static '/rsa/x_id/plotdata/temp.png %}
    – eugene
    Oct 28, 2013 at 10:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.