django 中式用靜態檔案(css,javascript)

來源:互聯網
上載者:User
Django模板中使用css, javascript

測試環境

(r'^css/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/var/www/django-demo/css'}),
(r'^js/(?P</path><path>.*)$', 'django.views.static.serve', {'document_root': '/var/www/django-demo/js'}),
(r'^images/(?P</path><path>.*)$', 'django.views.static.serve', {'document_root': '/var/www/django-demo/images'}),

模板中使用下述方式即可:

<link href="/css/demo.css" type="text/css" rel="stylesheet">

註:可採用os.path.dirname(globals()["__file__"])來獲得當前檔案所在路徑,比如

(r'^css/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.dirname(globals()["__file__"])+'/css'}),

可以使用os.path.abspath()函數返回此路徑的絕對路徑。

==============

要在django的tempalte file中引用css、js、gif等靜態檔案,首先一條setting.py中DEBUG開關開啟。
1、在project目錄下建立一個存放靜態檔案的目錄,如:medias
2、在url.py patterns中增加一行:
   (r'^site_media/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.STATIC_PATH}),
   還要from django.conf import setting
3、在setting.py中加入一行:
   STATIC_PATH='./medias'

如此設定後,就可以在template file 中引用media中存放的靜態檔案了,如:
   <img src='/site_media/django.gif'>


線上環境

在使用Django開發的Web項目中是避免不了使用css、javascript、js等靜態檔案的,而對於這些靜態檔案的處理,django官 網這樣寫:Django itself doesn’t serve static (media) files, such as images, style sheets, or video. It leaves that job to whichever Web server you choose.就是說django本身不處理類似於圖片、樣式表、視頻等靜態檔案,它將此項工作交給了你選擇的Web伺服器。

在網上搜尋到的django項目處理靜態檔案的樣本中,大家似乎都在使用如下的方法讓django處理靜態檔案:

?View Code PYTHON
urlpatterns += patterns('',
(r'^static/(?P.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)

而對於django.views.static.serve方法,django官網說得很清楚:Using this method is inefficient and insecure. Do not use this in a production setting. Use this only for development.就是說這種方法是低效且不安全的,不要在生產環境使用此方法,只在開發環境使用。

這時對於靜態檔案的處理,我們只能使用我們選擇的Web伺服器來處理了。比如使用nginx伺服器的話,可以如下設定:

先設定settings.py,如下,

設定settings.py

然後設定nginx的相應網站配置部分,如下,

配置nginx

相關文章

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.