[Django]-Heroku Django app not loading static files (404 Not Found)

6👍

Django does not support serving static files in production. However, the fantastic WhiteNoise project can integrate into your Django application, and was designed with exactly this purpose in mind.

pip install whitenoise    

add whitenoise to your requirements.txt
add this code in app/wsgi.py

from whitenoise.django import DjangoWhiteNoise
application = DjangoWhiteNoise(application)

7👍

I’ve spent some hours before I was able to figure out this. @VipinMohan solution works for whitenoise<4. However, in version 4+, WhiteNoise removes some options which were deprecated in the previous major release. For the record, I am using Django 2.1.

From the docs:

The WhiteNoise middleware should be placed directly after the Django SecurityMiddleware (if you are using it) and before all other middleware.

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

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
     # the next line of code is the one that solved my problems
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware'
]

Pay attention to the Note in the section of the provided link.

You might find other third-party middleware that suggests it should be given highest priority at the top of the middleware list. Unless you understand exactly what is happening you should ignore this advice and always place WhiteNoiseMiddleware above other middleware.

1👍

Add collectstatic to Procfile

web: python manage.py collectstatic --no-input; gunicorn myapp.wsgi --log-file - --log-level debug

Thanks to this stack overflow answer

1👍

WhiteNoise configuration should be changed if you use v4.0 or later.
Please refer this whitenoise-changelog

Leave a comment