user1025948
user1025948

Reputation:

Trouble displaying generated image in Django

View:

import numpy as np
import matplotlib.pyplot as plt
import os


def blah_view(request):

# BUILD GRAPH
fname = "blah.png"
path = "home/templates/home"
fullpath = os.path.join(path, fname)

# 7 different groups
ind = np.arange(7)
width = 0.35

fig, ax = plt.subplots()

# code omitted. Generate graph here

plt.savefig(fullpath)

return render_to_response("image.html", {"path": fullpath})

image.html:

<img src="{{ path }}" />

urls.py:

url(r'^blah$', blah_view, name="blah")

If I try to navigate to /blah, I get a 404 error when trying to render the image. I'm stumped. The image is in the correct path and exists.

I get a 404 error that 127.0.0.1:8000/home/templates/home/blah.png not found.

How can I display my generated image? Thanks in advance.

Upvotes: 0

Views: 60

Answers (1)

Siddharth Gupta
Siddharth Gupta

Reputation: 1613

It will be a better idea, to create your graph and store it in Media folder. You can then set your MEDIA_URL and MEDIA_ROOT. Django does not serve static file directly from the folders.

You can then configure your url.py to

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = patterns('',
    # ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Upvotes: 1

Related Questions