【问题标题】:Django can't see images in /media/ folderDjango 看不到 /media/ 文件夹中的图像
【发布时间】:2013-07-04 04:07:59
【问题描述】:

如果我把我的图像放在/media/ 文件夹中,它就不起作用。但如果我将它们放在“/static/”文件夹中,它就可以工作。

{% extends 'base.html' %}

{% block contain %}
    <h1>New Report</h1>
    <form id="create" method="POST" action="" enctype="multipart/form-data">{% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Confirm">
    </form>


    {% for report in reports %}
        <P> {{report.title}} </P> <br>
        <img src="{{STATIC_URL}}<name of the image>" width='100px' height='100px'> =====> I can see the image

        <img src="{{MEDIA_URL}} <name of the image>" width='100px' height='100px'> =====> I cant see the image

        <img src="/static/<name of the image>" width='100px' height='100px'> =====> I cant see the image

        <img src="/media/<name of the image>" width='100px' height='100px'> ====>>>> I cant see the image


    {% endfor %}
{% endblock %}

【问题讨论】:

  • 你如何部署你的 django 应用程序?
  • 但是我的图片不是静态文件。我的图像是来自我的报告模型的图像。当我将图像放入“媒体”文件夹时,我看不到图像,但是当我在“静态”文件夹中使用该图像时,我可以看到图像。真的很奇怪。
  • 这是一个静态文件。您的报告模型 ImageField 只是该文件的链接。看看我的回答。 Django 或您的网络服务器可能不知道您的媒体文件夹
  • 如果它是来自您的报表模型的图像,只需直接调用它,django 就会为您填写链接。

标签: python django image templates


【解决方案1】:

您确定 django 测试服务器(或 apache/nginx)知道您的媒体文件夹吗?

尝试将其添加到 urls.py(如果您使用的是开发服务器):

if settings.DEBUG:
    urlpatterns += patterns('',
        url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
            'document_root': settings.MEDIA_ROOT,
        }),
   )

【讨论】:

  • @Cris Towi,那么,请接受答案!点击投票分数下的这个大检查
【解决方案2】:

将图像放入您的静态文件夹中会起作用,因为静态文件夹中的文件会在网站上提供。这是一个潜在的解决方案,这个discussion 似乎表明它对于某些图像是合理的。在我的网站上,媒体文件夹中的图像位于/uploads/&lt;name of the image&gt;。这就是MEDIA_URL 的设置。但是我从不明确调用MEDIA_URL,因为我所有的图像都绑定到模型中,所以 django 会为我处理。我的猜测是仔细检查您存储图像的文件夹的名称,并确保您正在查看正确的位置。其次,我会确保模板中的 {{MEDIA_URL}} 不是 undefined

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-12
    • 2021-06-06
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    相关资源
    最近更新 更多