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

来源:互联网 发布:mac air 搜狗输入法 编辑:程序博客网 时间:2024/04/30 07:05


看看新闻网>看引擎>开源产品

发表于10小时前(2014-02-16 01:12)  
阅读(3) | 评论(0)

0人收藏此文章,

赞0

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

 view plaincopy

  1. import os  

  2. HERE = os.path.dirname(os.path.abspath(__file__))  

  3. HERE = os.path.join(HERE, ‘../’)  

2.在STATICFILES_DIRS中设置成这样:

 view plaincopy

  1. # Additional locations of static files  

  2. STATICFILES_DIRS = (  

  3.     # Put strings here, like ”/home/html/static” or ”C:/www/django/static”.  

  4.     # Always use forward slashes, even on Windows.  

  5.     # Don’t forget to use absolute paths, not relative paths.  

  6.     os.path.join(HERE, ‘static/’),  

  7. )  

3.在html文件中加入css,js等的路径:

 view plaincopy

  1. <link rel=“stylesheet” href=“/static/css/bootstrap.css” />  

  2. <link rel=“stylesheet” href=“/static/css/bootstrap-responsive.css” />  

  3. <script type=“text/javascript” src=“/static/js/jquery-1.10.2.js”></script>  

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

 view plaincopy

  1. TEMPLATE_DIRS = (  

  2.     os.path.join(os.path.dirname(__file__), ‘..’‘templates’).replace(‘\\’,’/’),  

  3.     os.path.join(‘templates’),  

  4. )  

设置我们的static路径为:

 view plaincopy

  1. # Additional locations of static files  

  2. STATICFILES_DIRS = (  

  3.     # Put strings here, like ”/home/html/static” or ”C:/www/django/static”.  

  4.     # Always use forward slashes, even on Windows.  

  5.     # Don’t forget to use absolute paths, not relative paths.  

  6.     os.path.join(os.path.dirname(__file__), ‘..’‘static’).replace(‘\\’,’/’),  

  7.     os.path.join(‘static’),  

  8. )  

OK了!虽然我们从网页不能访问那些静态文件,但是在我们项目中可以用这些静态文件了。


声明:OSCHINA 博客文章版权属于作者,受法律保护。未经作者同意不得转载。

No tags for this post.
除非注明,本站文章均为原创或编译,转载请注明: 文章来自KENGINE | Kankanews.com
0 0