2011-02-23 107 views
0

我偶然發現了Django的RequestContext的一個愚蠢的情況。這是我的問題:RequestContext爲我的imagaes返回404錯誤?

我將所有圖像存儲在我的媒體/上傳文件中。在我的模板,我簡單地使用:

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

,我有其中包含contextprocessor文件:

from django.conf import settings 

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

當我打開我的模板時,t他的圖像的路徑出現,但服務器給404,路徑似乎正確,但django無法爲他們提供服務。那麼,什麼原因導致我無法在模板上看到圖像?

圖像源顯示如下:

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

回答

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

MEDIA_ROOT是您的媒體的文件系統路徑,而不是URL路徑。建立從mongoose_za的建議,您的模板應該是這樣的:

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

當然,你也可以在settings.py相當於您所選擇的URL根定義一個新的常數,無論是在urls.py使用以及如在你的模板中。