Home > database >  request media files in django when the debug is false
request media files in django when the debug is false

Time:10-06

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

CodePudding user response:

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

CodePudding user response:

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

  • Related