您的位置:首页 > Web前端 > BootStrap

在django项目中加入像bootstrap这样的css,js等静态文件

2014-02-16 13:31 555 查看
在django中,urls.py将URL请求转给view.py中的函数,函数将计算后的结果转给templates中的某个xxx.html文件,最后xxx.html文件发给了客户,在客户的页面显示出来,这里,我总结下我怎么在html文件里放入css,js等静态文件。在这里以bootstrap为例加入其中。

首先,在项目中创建一个static文件夹,然后再在static文件夹里创建三个css,img,js文件夹。在里面对应放入我们下载的bootstrap的各个文件。放入的文件目前在网页里是找不到的哦~因为我们没有添加路径让系统找到它们,如下例子所示为找不到bootstrap文件:

http://127.0.0.1:8000/static/css/bootstrap.css

404 NOT FOUND



那怎么设置才能找到我们的bootstrap文件呢?很简单,只需在settings.py中进行设置就行。

方法一:

1.在头部加入:

[python] view plaincopy

import os

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了!虽然我们从网页不能访问那些静态文件,但是在我们项目中可以用这些静态文件了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: