在Django中,所有通过url申请的资源,都要在urls.py文件中进行配置。所以css,js,image等静态资源也不例外。
网上大部分给出的方案为:
settings.py中:
STATIC_ROOT=你的静态文件存放根目录
urlpatterns = patterns('django.views', url(r'^css/(?P<path>.*)$', 'static.serve', {'document_root':settings.STATIC_ROOT+'css/'}), url(r'^js/(?P<path>.*)$', 'static.serve', {'document_root':settings.STATIC_ROOT+'js/'}), url(r'^image/(?P<path>.*)$', 'static.serve', {'document_root':settings.STATIC_ROOT+'image/'}), )
但是这样,会出现一个灰常卵疼的问题——URL中最后的那个'/'会导致资源找不到。我们来问题重现。
===========================割========================开=============================
假如我的url配置如下:
urlpatterns += patterns('ued.views', url(r'^hello_world$', 'hello_world'), )
def hello_world(request): return render(request,'ued/hello_world.html',{'repeat':range(12),'crepeat':range(1,5)+[2]})
<html> <head> <title>Bootstrap 101 Template</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- Bootstrap --> <link href="css/bootstrap.min.css" rel="stylesheet" media="screen" /> </head> <body> <h1>Hello, world!</h1> <script src="http://code.jquery.com/jquery.js"></script> <script src="js/bootstrap.min.js"></script>
当我输入url:http://127.0.0.1:8000/hello_world/时,显然没有匹配,404错误。
当我输入url:http://127.0.0.1:8000/hello_world时,一切正常,静态资源都可以找到。
但是,修改url.py:
urlpatterns += patterns('ued.views', url(r'^hello_world/$', 'hello_world'), )
因为默认Django的APPEND_SLASH=True,所以不以'/'结尾的url,如果没有匹配url配置,将被重定向至尾部包含斜杠的相同字眼的URL。反之不行。
如果设置APPEND_SLASH=False,就不会重定向而是报404错误。
但是,网页显示样式错误,查看后台显示出这样的信息。
"GET /hello_world/css/bootstrap.min.css HTTP/1.1" 404 "GET /hello_world/js/bootstrap.min.js HTTP/1.1" 404也就是说,对于匹配的url规则中,以'/'结尾的配置。Django会这么处理,申请的静态资源自动把当前url前缀当作资源前缀。这么一来自然找不到资源了。
======================割=============================开===========================
我不知道大神们的解决办法是什么,我的方法很笨。
修改urls.py:
urlpatterns = patterns('django.views', url(r'css/(?P<path>.*)$', 'static.serve', {'document_root':settings.STATIC_ROOT+'css/'}), url(r'js/(?P<path>.*)$', 'static.serve', {'document_root':settings.STATIC_ROOT+'js/'}), url(r'image/(?P<path>.*)$', 'static.serve', {'document_root':settings.STATIC_ROOT+'image/'}), )
修改成以'css/.*'结尾url都被指向相应静态资源链接,而不是原来的既以它开头又以它结尾。
可是这个样子,还是会有问题,因为类似/xxxxcss/xxxxx之类的URL都被当成是css引用了。
因此,最终修改如下:
urlpatterns = patterns('django.views', url(r'/css/(?P<path>.*)$', 'static.serve', {'document_root':settings.STATIC_ROOT+'css/'}), url(r'/js/(?P<path>.*)$', 'static.serve', {'document_root':settings.STATIC_ROOT+'js/'}), url(r'/image/(?P<path>.*)$', 'static.serve', {'document_root':settings.STATIC_ROOT+'image/'}), )