【问题标题】:RequestContext returns 404 error for my imagaes?RequestContext 为我的图像返回 404 错误?
【发布时间】:2011-02-23 19:49:48
【问题描述】:

我偶然发现了 Django 的 RequestContext 事情的愚蠢情况。这是我的问题:

我将所有图像存储在我的媒体/上传文件中。在我的模板中,我只是在使用:

{% for photo in photos %}
  <a href="#"> <img src="{{gallery_root}}/{{photo.get_name}}" /></a>
{% endfor %}

我的看法是:

def gallery_view(request):
    photos = Photo.objects.all()
    return render_to_response('gallery/sampleGallery.html',{'photos':photos},context_instance=RequestContext(request))

在我的设置文件中:

GALLERY_ROOT = os.path.join(MEDIA_ROOT, "media/uploads")

我有一个上下文处理器文件,其中包含:

from django.conf import settings

def gallery_root(request):
    return {'gallery_root':settings.GALLERY_ROOT}

当我打开我的模板时,出现了图像的路径但是服务器给出了 404,路径似乎正确但 django 无法为它们提供服务.. 那么我在模板上看不到图像的原因是什么?

图像源如下所示:

<a href="#"> <img src="/Users/imperium/Desktop/sample/media/uploads/popo.jpg" /></a>  

【问题讨论】:

    标签: django http-status-code-404 requestcontext


    【解决方案1】:

    您好,可能是您的媒体没有得到适当的服务。 在你的 urls.py 文件中尝试这样的事情。

    # if we're in DEBUG mode, allow django to serve media
    # This is considered inefficient and isn't secure.
    from django.conf import settings
    if settings.DEBUG:
        urlpatterns += patterns('',
            (r'^media/(?P<path>.*)$', 'django.views.static.serve',
             {'document_root': settings.GALLERY_ROOT}),
        )
    

    【讨论】:

      【解决方案2】:

      MEDIA_ROOT 是媒体的文件系统路径,而不是 URL 路径。根据 mongoose_za 的建议,您的模板应如下所示:

      {% for photo in photos %}
        <a href="#"> <img src="/media/{{photo.get_name}}" /></a>
      {% endfor %}
      

      当然,您可以在 settings.py 中定义一个新常量,该常量对应于您选择的 URL 根,并在 urls.py 以及您的模板中使用它。

      【讨论】:

        猜你喜欢
        • 2015-06-02
        • 2018-12-11
        • 2019-08-16
        • 2015-01-04
        • 2014-01-26
        • 1970-01-01
        • 2015-02-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多