Django and Static Assets

Last Updated: 26 November 2014

assets collectstatic django python static

Table of Contents

Django settings for static assets can be a bit difficult to configure and debug. However, if you just add the following settings to your settings.py, everything should work exactly as expected:

settings.py

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'

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

Django won’t automatically create the target directory that collectstatic uses, so we recommend adding a dummy file to your repository, as seen here.

Whitenoise

By default, Django does not support serving static files in production. We recommend using the WhiteNoise project for best-practice serving of static assets in production.

Installing Whitenoise

$ pip install whitenoise
...
$ pip freeze > requirements.txt

settings.py

# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/

STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

wsgi.py

from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise

application = get_wsgi_application()
application = DjangoWhiteNoise(application)

Your application will now serve static assets directly from Gunicorn in production. This will be perfectly adequate for most applications, but top-tier applications may want to explore using a CDN with Django-Storages.

Automatic Collectstatic

When a Django application is deployed to Heroku, collectstatic is run automatically when it is configured properly.

Detection

We determine if collectstatic is configured by running the following against your codebase:

$ python manage.py collectstatic --dry-run --noinput

If required configurations are missing, this command will fail and no collectstatic support will be applied to your application.

Debugging

To learn more about why your application’s collectstatic isn’t configured, you can use heroku run:

$ heroku run python manage.py collectstatic --noinput
...
django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting.

Disabling Collectstatic

Sometimes, you may not want Heroku to run collectstatic on your behalf. You can disable collectstatic with the DISABLE_COLLECTSTATIC configuration:

$ heroku config:set DISABLE_COLLECTSTATIC=1