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

來源:互聯網
上載者:User

標籤: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,圖片等外部檔案的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.