4

I'm reading the book Matplotlib for Python Developers but am struggling to follow the example in the section "Matplotlib in a Django application" in chapter 8.

So far, I've issued the command

django-admin startproject mpldjango

and, in the mpldjango directory,

python manage.py startapp mpl

As per the example, in mpldjango/mpl I've made the views.py as follows:

import django
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import numpy as np

def mplimage(request):
    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    x = np.arange(-2,1.5,.01)
    y = np.sin(np.exp(2*x))
    ax.plot(x, y)
    response=django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

Next, the book says that the mpldjango/urls.py should have this line added to it:

urlpatterns = patterns('',
       (r'mplimage.png', 'mpl.views.mplimage'),
)

However, I don't see how this would work since in the 'default' urls.py, urlpatterns is a lits of django.conf.urls.url objects:

from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]

and there is no patterns constructor defined. Perhaps this book (which is from 2009) is referring to a legacy Django API? If so, how would I modify this code to make it work? (That is, after python manage.py runserver I should be able to browse to localhost:8000/mplimage.png and see an image of a chirped sinusoid).

1 Answer 1

7

According to cannot import name patterns this is indeed a legacy interface of Django. I 'updated' it by making mpldjango/urls.py as follows:

from django.conf.urls import include, url
from django.contrib import admin
import mpl.views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'mplimage.png', mpl.views.mplimage),
]

Now if I browse to http://localhost:8000/mplimage.png I see the plot as desired:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.