Search code examples
djangodjango-media

Django not serving media files if I check for settings.DEBUG


This serves the media files correctly:

urlpatterns = [
...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

This doesn't serve the media files:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [ ... ] 

if settings.DEBUG:
    urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

The documentation writes "This is not suitable for production use!", so that is why I need a way to check for DEBUG before serving media files. How can I do that. Why does this approach doesn't work?


Solution

  • Use

    if settings.DEBUG:
        urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    

    (notice '=' after '+' - in your version you are adding static() patterns but not assigning the result to the urlpatterns variable)