1

参考我的上一个问题只能将元组(不是“unicode”)连接到元组

现在,当我尝试在媒体文件的URL获取请求时,出现以下错误。

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

网址.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}),
                       ) 
4

1 回答 1

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/'

在 urls.py 里面的子目录 django_site/

#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/在某个时候定义 url 才能从MEDIA_URL. 我没有在文档中明确看到这一点,但是,除非您配置 url 路由,否则 GET 请求似乎总是失败。现在,我从模板中或直接通过 url 提取文件。希望这可以帮助!

于 2013-12-30T17:47:04.720 回答