標籤:csdn nes root sys show sts app parent http
Django加入JS,CSS。圖片等外部檔案的方法By 白熊花田(http://blog.csdn.net/whiterbear) 轉載需註明出處,謝謝。
在使用Django搭建網站時,往往須要使用一些js,css或者圖片等外部檔案,這裡給出使用它們的使用方法。
我的django版本號碼為:1.8.2
如果我們有project例如以下:
sentiment_analysis
|-mysite
| |-mysite
| |-manage.py
| |-show_pages
| | |-__init__.py
| | |-admin.py
| | |-models.py
| | |-tests.py
| | |-urls.py
| | |-views.py
| | |-tests.py
| | |-templates
| | | |-show_pages
| | | | |-index.html
在此project下。如果我們須要在index.html中使用js等外部檔案,能夠按例如以下步驟進行使用。
加入外部檔案
在應用show_pages(與manage.py同級)中建立static檔案夾,裡面放置外部資源檔(css,js等)。
改動settings.py
在settings.py檔案裡加入例如以下幾行(當中有一行已經存在了)。
STATIC_ROOT= os.path.join(os.path.dirname(os.path.dirname(file)),’static’).replace(‘\’,’/’)
STATIC_URL = ‘/static/’
TEMPLATE_DIRS = (
‘/show_pages/templates’,
)
改動urls.py
改動mysite檔案夾下的urls.py檔案為:
from django.contrib import admin
from django.conf.urls import *
from django.conf import settings
urlpatterns = [
url(r’^admin/’, include(admin.site.urls)),
url(r’^show_pages/’, include(‘show_pages.urls’)),
url(r’^static/(?P.*)$’,’django.views.static.server’,{‘document_root’:settings.STATIC_ROOT},name=’static’),
]
改動manage.py
改動mysite檔案夾下的manage.py檔案,加入:
reload = reload(sys)
sys.setdefaultencoding(‘gb18030’)#否則載入css檔案仍會出錯
引用
最後,在index.html中引入外部資源檔時,使用例如以下方式進行引用:
- js檔案:
<script src="/static/js/jquery.js"></script>
- css檔案:
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
- 圖片:
<img class="img-responsive" src="/static/img/phones.png" >
或者進行例如以下引用:
先在index.html檔案裡輸入:{% load staticfiles %},再按例如以下方式進行引用。
- js檔案:
<script src="{% static ‘js/jquery.js‘ %}"></script>
- css檔案:
<link href="{% static ‘css/bootstrap.min.css‘ %}" rel="stylesheet">
- 圖片:
<img class="img-responsive" src="{% static ‘img/phones.png‘ %}" >
Django加入JS,CSS,圖片等外部檔案的方法