我正在创建一个 Django 项目。我刚刚尝试将项目退出调试,DEBUG = False
由于某种原因,我所有的静态文件都没有显示出来。他们给出的错误代码为 500。我该如何解决这个问题?
一些settings.py:
DEBUG = True
TEMPLATE_DEBUG = DEBUG
...
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
最佳答案
静态文件应用程序未在 DEBUG=False
中自动提供静态媒体模式。来自 django.contrib.staticfiles.urls
:
# Only append if urlpatterns are empty
if settings.DEBUG and not urlpatterns:
urlpatterns += staticfiles_urlpatterns()
您可以通过附加到
urlpatterns
来提供它手动或使用服务器来提供静态文件(就像在非 Debug模式下运行 Django 项目时应该那样)。虽然我想知道的一件事是为什么你得到一个 500 状态码响应而不是 404。在这种情况下有什么异常(exception)?
编辑
因此,如果您仍想通过 staticfiles 应用程序提供静态文件,请将以下内容添加到您的根 url conf (
urls.py
):if settings.DEBUG is False: #if DEBUG is True it will be served automatically
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
)
不过,您需要记住一些事情:
STATIC_ROOT
中。 (manage.py collectstatic
)。见staticfiles app docs了解更多信息。这是必要的,因为您在非 Debug模式下运行。 from django.conf import settings
在您的 urls.py
:) 关于django - 在 Django 中退出调试时不会加载静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6405173/