Django 配置访问静态文件
1.settings.py
首先在 settings 文件中,引用 os 模块:
import os
定义根目录:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
启用静态文件模块:
INSTALLED_APPS = (
'django.contrib.staticfiles',
)
定义静态文件 URL 标识:
STATIC_URL = '/static/'
定义静态文件目录:
STATIC_ROOT= os.path.join(BASE_DIR,'static')
2.urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_ROOT },name="media"),
)
3.调用示例
<link rel="stylesheet" type="text/css" href="/static/admin/css/base.css" />
<link rel="stylesheet" type="text/css" href="/static/admin/css/dashboard.css" />
<script type="text/javascript">window.__admin_media_prefix__ = "/static/admin/";</script>
说明:需要将 admin 模块中的静态文件拷贝到根目录的 static 目录下。