在Django中找不到静态媒体图像

时间:2013-09-28 17:41:27

标签: python django

参考我以前的问题can only concatenate tuple (not "unicode") to tuple

现在,当我在媒体文件的网址上尝试 GET请求时,我收到以下错误。

Page not found (404)
Request Method: GET
Request URL:    http://localhost:8000/media/media/abyss.jpg

Urls.py

urlpatterns = patterns('',
                       url(r'^admin/', include(admin.site.urls)),
                       url(r'^$', 'blog.views.index'),
                       url(r'^blog/(?P<slug>[\w\-]+)/$', 'blog.views.article'),
                       url(r'^(.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
                       ) 

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,这就是我要解决的问题: 我的项目结构

./django_site
   app1/ 
   app2/
   media/
   django_site/
     settings.py
     #your other basic config stuff in here

在settings.py中:

MEDIA_ROOT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'media')
MEDIA_URL = '/media/'

在子目录django_site /

中的urls.py中
#the main url patterns
urlpatterns = patterns('',
#urls
)

"""Here's where we're putting the route to serve media from MEDIA_URL. 
I couldn't get this part to work inside the inital declaration of urlpatterns. 
Maybe you'll have better luck """

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

然后在模板中:

<img src="{{ MEDIA_URL }}{{ image_name }}" height="200" width="400"/>

我从基于函数的视图传递image_name。如图所示,您必须在某个时刻定义http://somesite.com/media/网址,以便能够从MEDIA_URL提取媒体。我没有在文档中明确地看到这一点,但是,除非配置url路由,否则GET请求似乎总是失败。现在,我从模板中或直接通过url拉取文件。希望这有帮助!