django使用靜態檔案二

來源:互聯網
上載者:User

  這邊文章是我在豆瓣網上看到的,由於它把django項目的靜態檔案和資源檔都處理了,感覺比較好,我試了,蠻好的。下面就是內容,我簡單的整理了下:

  在django1.3中,提供了django.contrib.staticfiles這個模組,方便使用靜態檔案,顯示圖片,使用css等。在設定時需要注意的是:

1.MEDIA_ROOT  MEDIA_URL2.STATIC_ROOT STATIC_URL3.ADMIN_MEDIA_ROOT4.STATICFILES_DIRS

  具體步驟為:

  1.在settings.py中添加與修改:

# static/file operationHERE = os.path.dirname(os.path.dirname(__file__))# Absolute filesystem path to the directory that will hold user-uploaded files.# Example: "/home/media/media.lawrence.com/media/"#MEDIA_ROOT = ''MEDIA_ROOT = os.path.join( HERE , 'media/').replace('\\','/')# URL that handles the media served from MEDIA_ROOT. Make sure to use a# trailing slash.# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"#MEDIA_URL = ''MEDIA_URL = '/media/'# Absolute path to the directory static files should be collected to.# Don't put anything in this directory yourself; store your static files# in apps' "static/" subdirectories and in STATICFILES_DIRS.# Example: "/home/media/media.lawrence.com/static/"STATIC_ROOT = ''STATIC_PATH = os.path.join( HERE , 'static').replace('\\','/')# URL prefix for static files.# Example: "http://media.lawrence.com/static/"STATIC_URL = '/static/'# add property : ADMIN_MEDIA_ROOT BY slider# ADMIN_MEDIA_ROOT = '/static/admin/' # Additional locations of static filesSTATICFILES_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.    os.path.join(HERE,'static').replace('\\','/'),)

  項目urls.py裡的代碼:

from django.conf import settingsif settings.DEBUG:     urlpatterns += patterns('',             (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_PATH, 'show_indexes':True}),             ) 

  然後在模板裡面這樣引用(這裡css檔案的目錄是 : 項目目錄/static/forum/csss/base.css):

<link rel="stylesheet" type="text/css" href="/static/forum/css/base.css"/>

  順便說一下:

MEDIA_ROOT 用於存放user上傳的東西 STATIC_ROOT用於存放網站自己的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.