【问题标题】:Trouble displaying generated image in Django在 Django 中无法显示生成的图像
【发布时间】:2015-05-29 20:28:04
【问题描述】:

查看:

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")

如果我尝试导航到 /blah,我会在尝试渲染图像时收到 404 错误。我难住了。图像在正确的路径中并且存在。

我收到 127.0.0.1:8000/home/templates/home/blah.png 未找到的 404 错误。

如何显示我生成的图像?提前致谢。

【问题讨论】:

  • 您是否从 Django 访问的目录(即您的静态或媒体文件目录)提供该图像?

标签: python html django image


【解决方案1】:

创建图表并将其存储在 Media 文件夹中会更好。然后您可以设置您的 MEDIA_URL 和 MEDIA_ROOT。 Django 不直接从文件夹中提供静态文件。

然后您可以将您的 url.py 配置为

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 2020-03-19
    • 2012-05-15
    • 2020-08-20
    • 2017-07-05
    • 2012-07-02
    • 1970-01-01
    相关资源
    最近更新 更多