# Django static and media files not working when debug is false
In this article you will learn how to fix problem of not loading static files and media in Django even the DEBUG is FALSE. This is the easiest and safest solution.
# Problem:
Django static and media files not working when debug is false
➤ Code: settings.py
DEBUG = False #True
ALLOWED_HOSTS = ['*'] #Host name
# Problem Fix:
Let's see, How you can fix the problem of Django static and media files not working when DEBUB = False :
1.)First way: devserver in insecure mode
If you still need to server static locally (e.g. for testing without debug) you can run devserver in insecure mode:
python manage.py runserver --insecure
--insecure: it means you can run server without security mode.
Note: This is Exactly you must type on terminal to run your project without "DEBUG = TRUE" and then you see all assets (static) file is loading correctly On local server.
2.)Second way: devserver in secure mode
Step 1 : Define a STATIC_ROOT and MEDIA_ROOT path in settings.py.
➤ Code: settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
if DEBUG:
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
else:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Step 2 : Now define your URLConf that if static is in the beginning of url, access files from the static folder staticfiles.
➤ Code: urls.py
from django.conf.urls import url
from django.conf import settings
from django.views.static import serve
urlpatterns = [
url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT}),
]
Note: This is your project's urls.py file.
Step 3 : Now you can run your django project.
python manage.py runserver
Note : Congratulations, now static and media files will be loaded in your Django project when DEBGU = False. Have fun!
Comments
PLease help
contact: saitwalsamir@gmail.com
Complete integration of the mobile app and the website gives the businesses a boost not only in their growth but also in the revenue.
Top Mobile App Development Company in Delhi
Thanks again
cannot import name 'url' from 'django.conf.urls'
machine server
location /media/ {
alias /home/xuser/xproject/media/;
expires 1d;
}
django.conf.urls.url() was deprecated in Django 3.0, and is removed in Django 4.0+.
so you only have to update the import and replace url with re_path.