0

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

  • Does this answer your question? [Why does DEBUG=False setting make my django Static Files Access fail?](https://stackoverflow.com/questions/5836674/why-does-debug-false-setting-make-my-django-static-files-access-fail) – Tim Oct 04 '22 at 21:17
  • please check my answer here, good luck https://stackoverflow.com/a/73928488/18806558 – Hashem Oct 05 '22 at 07:58

2 Answers2

1

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

0

When DEBUG=False, local files will not be accessible. You need to try any online storage for static and media files e.g. AWS S3 bucket etc.

Guide:

https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html

  • Thanks, I found the answer I want to set my host to be as storage also for media folder –  Oct 06 '22 at 08:12