這邊文章是我在豆瓣網上看到的,由於它把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,圖片