Django添加JS,CSS,圖片等外部檔案的方法

來源:互聯網
上載者:User
Django添加JS,CSS,圖片等外部檔案的方法 By 白熊花田(http://blog.csdn.net/whiterbear) 轉載需註明出處,謝謝。

在使用Django搭建網站時,往往需要使用一些js,css或者圖片等外部檔案,這裡給出使用它們的用法。
我的django版本為:1.8.2
假設我們有工程如下:
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

在此工程下,假設我們需要在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" alt="">

或者進行如下引用:

先在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' %}" alt="">

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.