在django項目中加入像bootstrap這樣的css,js等靜態文件

  在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

  1. import os  bootstrap

  2. HERE = os.path.dirname(os.path.abspath(__file__))  瀏覽器

  3. HERE = os.path.join(HERE, '../')  


2.在STATICFILES_DIRS中設置成這樣:

[python] 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等的路徑:

[html] 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的路徑樣式:

[python] view plaincopy

  1. TEMPLATE_DIRS = (  

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

  3.     os.path.join('templates'),  

  4. )  


設置咱們的static路徑爲:

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

相關文章
相關標籤/搜索