settings.py
STATIC_URL = '/static/'
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'staticfiles')]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'data')
MEDIA_URL = '/data/'
urls.py
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
handler404 = 'generic.views.invalid_request'
When I set DEBUG=False and run the server using
python manage.py runserver --insecure
all static file are serve successfully but media files doesn't appear. In debug console media urls raise error 500.
static
helper function does not work in DEBUG=False mode. And should not. Serving static/media files with Django in prod is not recommended. Configure your webserver (Nginx, Apache,..) to serve these files.
error 500
- investigate log files to understand what causes app failure.
static file are serve successfully
perhaps they are being taken from browsers cache.
I had been Using WhiteNoise which allows your web app to serve its own static files, making it a self-contained unit that can be deployed anywhere without relying on nginx, Amazon S3 or any other external service.
1 - Install with pip:
pip install whitenoise
2 - Edit your settings.py
file and add WhiteNoise to the MIDDLEWARE_CLASSES
list, above all other middleware apart from Django’s SecurityMiddleware
:
MIDDLEWARE = [
# 'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
# ...
]
Thats All you need to serve static files without configuring any third party server.
来源:https://stackoverflow.com/questions/55842323/django-media-files-doesnt-work-when-debug-false