在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了!雖然咱們從網頁不能訪問那些靜態文件,可是在咱們項目中能夠用這些靜態文件了。