RequestContext为我的图片返回404错误?

时间:2011-02-23 19:49:49

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

我偶然发现了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>  

2 个答案:

答案 0 :(得分: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}),
    )

答案 1 :(得分:1)

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

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

当然,您可以在settings.py中定义一个与您选择的网址根相对应的新常量,并在urls.py和模板中使用此常量。