Static File not Working When debug is False in Django

HermantoXYZ
Aug 17, 2024

--

When DEBUG is set to False in a Django project, static files might not work as expected if the configuration is not correctly set up. Here are some steps to ensure your static files are served correctly when DEBUG is False:

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
from django.urls import include, path, re_path
from django.views.static import serve

urlpatterns = [
re_path(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
re_path(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
]

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

Configure STATIC_ROOT:

In your settings.py, set the STATIC_ROOT to the directory where you want Django to collect static files.

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

And..

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Referensi:

https://www.youtube.com/watch?v=C-3NaU7ra8o

--

--

No responses yet