1
votes

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.

3
Is your problem solved? - ans2human
yah done. @ans2human - Rafiul Islam
Accept the answer that helped you for other readers. - ans2human

3 Answers

1
votes

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.

0
votes

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.

0
votes

In order to serve MEDIA_URL when DEBUG is False (and without a third party lib), you can just do something like this:

  from django.views.static import serve as mediaserve
  urlpatterns.append(url(f'^{settings.MEDIA_URL.lstrip("/")}(?P<path>.*)$',
                     mediaserve, {'document_root': settings.MEDIA_ROOT}))