在django中,urls.py将URL请求转给view.py中的函数,函数将计算后的结果转给templates中的某个xxx.html文件,最后xxx.html文件发给了客户,在客户的页面显示出来,这里,我总结下我怎么在html文件里放入css,js等静态文件。在这里以bootstrap为例加入其中。javascript
首先,在项目中建立一个static文件夹,而后再在static文件夹里建立三个css,img,js文件夹。在里面对应放入咱们下载的bootstrap的各个文件。放入的文件目前在网页里是找不到的哦~由于咱们没有添加路径让系统找到它们,以下例子所示为找不到bootstrap文件:css
http://127.0.0.1:8000/static/css/bootstrap.css
html
404 NOT FOUNDjava
那怎么设置才能找到咱们的bootstrap文件呢?很简单,只需在settings.py中进行设置就行。python
方法一:jquery
1.在头部加入:apache
[python] view plaincopydjango
import os bootstrap
HERE = os.path.dirname(os.path.abspath(__file__)) 浏览器
HERE = os.path.join(HERE, '../')
2.在STATICFILES_DIRS中设置成这样:
[python] view plaincopy
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(HERE, 'static/'),
)
3.在html文件中加入css,js等的路径:
[html] view plaincopy
<link rel="stylesheet" href="/static/css/bootstrap.css" />
<link rel="stylesheet" href="/static/css/bootstrap-responsive.css" />
<script type="text/javascript" src="/static/js/jquery-1.10.2.js"></script>
<script type="text/javascript" src="/static/js/bootstrap.js"></script>
4.在浏览器中继续输入以上网址,看看能不能获取到css文件:
http://127.0.0.1:8000/static/css/bootstrap.css在浏览器中就能够看到:
/*! * Bootstrap v2.3.2 * * Copyright 2012 Twitter, Inc * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Designed and built with all the love in the world @twitter by @mdo and @fat. */
OK了!获得了咱们想要的内容,说明能够访问那些静态文件了,咱们在项目中也就能够用相对路径去用这些静态文件了。
方法二:
这个方法就更简单了,咱们根据templates的路径样式,设置static的路径。
先看看templates的路径样式:
[python] view plaincopy
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\','/'),
os.path.join('templates'),
)
设置咱们的static路径为:
[python] view plaincopy
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(os.path.dirname(__file__), '..', 'static').replace('\\','/'),
os.path.join('static'),
)
OK了!虽然咱们从网页不能访问那些静态文件,可是在咱们项目中能够用这些静态文件了。