【发布时间】:2020-06-12 17:32:30
【问题描述】:
我对访问django的静态文件有些疑惑。
版本:1.8.4
settings.py 中的 VAR:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = join(PROJECT_ROOT, 'static')
STATIC_URL = '/static/'STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
# insert your TEMPLATE_DIRS here
# os.path.join(BASE_DIR, 'templates').replace('\\', '/')
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
# list if you haven't customized them:
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
],
},
},
]
设置 STATICFILES_DIRS,并将
django.template.context_processors.static添加到TEMPLATES中的 context_processors,因此我可以在模板中使用“静态”标签。像:src="{{STATIC_URL}}js/example.js"或src="{% static 'js/example.js' %}"这样的 src 标签将生成一个指向http://myhost/static/js/example.js的 url。如果我想在 app 目录中加载静态文件,我应该怎么做?根据我对 django-official-doc 的理解,
STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django.contrib.staticfiles.finders.FileSystemFinder', )
默认情况下,查找器将搜索app/static,但如果app/templates/index.html中的src="static/js/example.js",服务器将返回404 代码。直到我将urlpatterns += staticfiles_urlpatterns()添加到app/urls.py。
我想知道的是:
为什么是 404?加载静态文件表单时
app/static不带urlpatterns += staticfiles_urlpatterns()。如果我想在
app/static中获取静态文件,如何灵活编写url?因为{{STATIC_URL}}或{% static %}都指向项目/静态。
我花了几个小时阅读有关 stackoverflow 的相关帖子。非常感谢任何帮助。
【问题讨论】:
-
看
simpleform.urlsstackoverflow.com/a/26654433/3033586