1

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.

Sangram
  • 354
  • 1
  • 12
Rafiul Islam
  • 393
  • 2
  • 6

3 Answers3

1

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.

Ivan Starostin
  • 8,798
  • 5
  • 21
  • 39
0

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.

ans2human
  • 2,300
  • 1
  • 14
  • 29
  • WhiteNoise is not supposed to serve media files, only static files. It only serves files that exist when the server is started, so for that reason it's not suitable for media files. – damd Dec 20 '21 at 12:15
0

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}))
slumtrimpet
  • 3,159
  • 2
  • 31
  • 44