Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

debugging - Static files won't load when out of debug in Django

I'm creating a Django project. I just tried taking the project out of debug, DEBUG = False and for some reason all my static files do not show up. They give an error code of 500. How do i fix this?

some of 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',
)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Static files app is not serving static media automatically in DEBUG=False mode. From django.contrib.staticfiles.urls:

# Only append if urlpatterns are empty
if settings.DEBUG and not urlpatterns:
    urlpatterns += staticfiles_urlpatterns()

You can serve it by appending to your urlpatterns manually or use a server to serve static files (like it is supposed to when running Django projects in non-DEBUG mode).

Though one thing I am wondering is why you get a 500 status code response instead of 404. What is the exception in this case?

EDIT

So if you still want to serve static files via the staticfiles app add the following to your root 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}),
    )

Some things you need to keep in mind though:

  • don't use this on a production environment (its slower since static files rendering goes through Django instead served by your web server directly)
  • most likely you have to use management commands to collect static files into your STATIC_ROOT (manage.py collectstatic). See the staticfiles app docs for more information. This is simply necessary since you run on non-Debug mode.
  • don't forget from django.conf import settings in your urls.py :)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...