Search code examples
pythondjangowebdjango-settingsdjango-media

request media files in django when the debug is false


i tried to set media root and media url in but when the debug is false don't return anything

settings.py

...
DEBUG = False

ALLOWED_HOSTS = [
    '127.0.0.1',
    '0.0.0.0',
    ...
]
...
STATIC_URL = 'static/'
STATICFILES_DIRS = [
    BASE_DIR / "static",
]
STATIC_ROOT = BASE_DIR / 'staticfiles'

MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = 'media/'

urls.py

...
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
...

What should i do to return media files in my projects


Solution

  • I found the answer

    urls.py

    ...
    from django.urls import re_path
    from django.conf import settings
    from django.conf.urls.static import static
    from django.views.static import serve
    ...
    urlpatterns = [
        ...
        re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
        ...
    ]
    ...
    
    # urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    ...
    

    This re_path function will can request all the files in the MEDIA_ROOT in settings.py