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

        在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.在头部加入:

import os
HERE = os.path.dirname(os.path.abspath(__file__))
HERE = os.path.join(HERE, '../')

2.在STATICFILES_DIRS中设置成这样:

# 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等的路径:

<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的路径样式:

TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\','/'),
    os.path.join('templates'),
)

设置我们的static路径为:

# 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了!虽然我们从网页不能访问那些静态文件,但是在我们项目中可以用这些静态文件了。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值