django1.10使用本地静态文件

django1.10使用本地静态文件方法 

本文介绍的静态文件使用,是指启动web站点后,访问静态资源的用法,实际静态资源地址就是一个个的url
如果没有启动web站点,只是本地调试html页面,那直接用相对路径访问资源即可
 
1.settings.py中加入下面两句话(应该是默认的,不需要增加)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
 
说明:
1.STATIC_URL为访问静态资源的链接,比如127.0.0.1/static/文件
2.STATIC_ROOT为访问静态资源文件的目录,BASE_DIR为根目录,可以打印一下看看。然后后面跟的是具体的子目录
比如我用的是根目录下的webManage/static目录
STATIC_ROOT = os.path.join(BASE_DIR, 'webManage/static')
 
2.配置urls.py文件
from django.views import static
from 工程目录 import settings
 
url(r'^static/(?P<path>.*)$', static.serve, {'document_root':settings.STATIC_ROOT}, name='static'),
 
3.访问静态资源
静态资源链接:根据STATIC_URL定义的值作为前缀,后面跟具体文件名
静态文件放置位置:STATIC_ROOT下的文件夹内
 
比如我文件放在了STATIC_ROOT/js/pie.js下,我可以像下面这样调用pie.js文件
<script src="/static/js/pie.js"></script>

遇到的问题 

问题1:
django 1.10 urls.py配置static静态文件的链接
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}, name='static'),
报错:raise TypeError('view must be a callable or a list/tuple in the case of include().')
 
解决方法:
改成下面的 格式
from django.views import static
from 工程目录 import settings
url(r'^static/(?P<path>.*)$', static.serve, {'document_root':settings.STATIC_ROOT}, name='static'),
 
原因:django 1.10 url的格式变了,需要引入view对象,然后调用view对象中的方法,不能直接用字符串的形式了
 
参考文档:
 
 
问题2:
访问静态文件时,报下面的错误
django.core.exceptions.ImproperlyConfigured: The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting
 
解决方法:
修改settings.py文件,将STATICFILES_DIRS中包含的STATIC_ROOT的路径删除掉
 
比如我的STATICFILES_DIRS原来包含了../webManage/static/,而我实际上是用这个地址作为我的静态资源文件地址
STATICFILES_DIRS = (
    # 动态的获取static文件的路径,注释掉STATIC_ROOT的路径
    # os.path.join(os.path.dirname(__file__), '../webManage/static/').replace('\', '/'),
    os.path.join(os.path.dirname(__file__), '../static/').replace('\', '/'),
    os.path.join(os.path.dirname(__file__), '../static/js/').replace('\', '/'),
)
原文地址:https://www.cnblogs.com/meitian/p/6897053.html