各類 django 靜態文件的配置總結【待續】

最近在學習django框架的使用,想引用靜態css文件,怎麼都引用不到,從網搜了好多,大多由於版本問題,
和我如今的使用的dango1.1配置不一樣,根據資料和公司的項目最終解決,因而想整理總結下各版dango靜態文件的配置,以備後查;css

配置緣由:因爲django不處理靜態文件(css、js、image等),而是交與web服務器處理。
而django的路徑處理和其餘web框架有些區別,它須要咱們手動的配置靜態文件的路徑,而不能直接引用。html

靜態文件的配置的分兩種
    第一種爲django的開發服務器的配置
    第二種是生產服務器的nginx或apache的web服務配置python

第一種,django的開發服務器的靜態文件配置,根據django版本的不一樣,有着比較大的區別。
    dango 1.1靜態文件配置:
        一、在項目目錄中同settings目錄創建static文件夾,其中存放 js 、css 、images文件,可再單首創建文件存放。jquery

個人文件路徑:nginx

        二、在settings中增長靜態文件目錄配置:web

STATIC_PATH = os.path.join( os.path.dirname(__file__) , 'static' )

        三、在url.py 中增長靜態文件的路徑 :apache

# u靜態文件

urlpatterns += patterns('',

     #(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_PATH}),  

     (r'^images/(?P<path>.*)$' , 'django.views.static.serve', 

        {'document_root': os.path.join( settings.STATIC_PATH , 'images' ) } ) ,

     (r'^css/(?P<path>.*)$' , 'django.views.static.serve', 

        {'document_root': os.path.join( settings.STATIC_PATH , 'css' ) } ) ,

     (r'^js/(?P<path>.*)$' , 'django.views.static.serve', 

        {'document_root': os.path.join( settings.STATIC_PATH , 'js' ) } ) ,  

 )

          四、在模板中引用:django

<link href="/css/bootstrap.min.css" rel="stylesheet">
<script src="/js/ie-emulation-modes-warning.js"></script>

主要是路徑的問題,其餘路徑應該也可應,好比url.py中的直接使用start/來做爲url,如下均匹配,以驗證:bootstrap

# 匹配static 文件夾及子文件夾中的文件
(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_PATH}),  
# 匹配image中的文件
#(r'^images/(.*)$' , 'django.views.static.serve', {'document_root': os.path.join( settings.STATIC_PATH , 'images' ) } ) ,
# 配置css文件價中的文件及子文件夾中的文件
#(r'^css/(?P<path>.*)$' , 'django.views.static.serve', {'document_root': os.path.join( settings.STATIC_PATH , 'css' ) } ) ,
#(r'^js/(?P<path>.*)$' , 'django.views.static.serve', {'document_root': os.path.join( settings.STATIC_PATH , 'js' ) } ) ,

 

    django 1.3 靜態文件配置:瀏覽器

      django1.3提供了django.contrib.staticfiles這個模塊,方便使用靜態文件,顯示圖片,使用css等。

默認狀況下(若是沒有修改STATICFILES_FINDERS的話),Django首先會在STATICFILES_DIRS配置的文件夾中尋找靜態文件,而後再從每一個app的static子目錄下查找,而且返回找到的第一個文件。

settings中新增的配置,MEDIA_ROOT、 MEDIA_URL 、STATIC_ROOT  、STATIC_URL

MEDIA:指用戶上傳的文件,好比在Model裏面的FileFIeld,ImageField上傳的文件。若是你定義
MEDIA_ROOT=c:\temp\media,那麼File=models.FileField(upload_to="abc/"),上傳的文件就會被保存到c:\temp\media\abc。MEDIA_ROOT必須是本地路徑的絕對路徑。

MEDIA_URL是指從瀏覽器訪問時的地址前綴。

STATIC_ROOT用於存放網站本身的js,css,圖片

   注意:不要把你項目的靜態文件放到這個目錄。這個目錄只有在運行manage.py collectstatic時纔會用到。 Don't put anything in this directory(STATIC_ROOT) yourself; store your static files  in apps' "static/" subdirectories and in STATICFILES_DIRS.

STATIC_URL的含義與MEDIA_URL相似 

參考步驟以下:

          一、settings配置:

HERE=os.path.dirname(os.path.dirname(__file__)
MEDIA_ROOT=os.path.join( HERE , 'media').replace('\\','/')
MEDIA_URL = '/media/'
STATIC_ROOT =os.path.join( HERE , 'static').replace('\\','/')
STATIC_URL= '/static/'
ADMIN_MEDIA_ROOT = '/static/admin/' 
STATICFILES_DIRS = (
       os.path.join(HERE,'app1/static/').replace('\\','/'),
       os.path.join(HERE,'app2/static/').replace('\\','/')
)

         二、url的配置:

from django.conf import settings
from djagno.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL , document_root = settings.MEDIA_ROOT )
urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT )

        三、模板的引用:

{% load static %}
<img src="{{ get_static_prefix }}images/1.jpg" />
<link href="{get_static_prefix}}css/truple.css />

具體配置,視狀況而定,並不必定如此配置,僅供參考,待驗證--todo;

django 1.3 日後的靜態配置目錄結構及方法變更比較小。

django1.4 靜態配置:

url.py 增長:

## django 自動處理靜態文件, 在模板框中可直接經過 static/ 引用
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()

setting.py 配置:

BASEPATH = os.path.join( os.path.dirname( os.path.abspath(__file__) ) ,'..')

MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = os.path.join( BASEPATH, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    #'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)


import os
TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\','/'),)
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'myapp',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

模板文件:

    <link rel="stylesheet" href="static/css/my.css">
    <script src="static/js/jquery.js"></script>

待總結--todo

第二種 生成服務器的配置:

nignx的靜態文件的配置:

todo

Apache的靜態文件的配置:

todo

參考文檔:
http://blog.sina.com.cn/s/blog_3fe961ae01016fpk.html
http://ddtcms.com/news/2011/11/21/18/django-1-3-zhong-xian-shi-tu-pian-shi-yong-jing-tai-wen-jian-de-wen-ti-django-static-files/       
http://blog.csdn.net/wenxuansoft/article/details/8580508

相關文章
相關標籤/搜索