Django static files not working when debug false || debug true
3 min
Ankaj Gupta
March 25, 2021

Django static files not working when debug false || debug true

Django static not working when debug is false

# 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 DEBUG = 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 what 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 DEBUG = False. Have fun!

django django static files

Related Posts