TExcelTAD
Home › Django › Django Static Files

Django Static Files

Web pages need more than HTML: stylesheets, JavaScript, images and fonts. Django calls these static files — files that are the same for every visitor and are shipped with your code. (Files uploaded by users are called media files and are handled separately.) The django.contrib.staticfiles app helps you organise them during development and collect them for production.

Static files Media files
Who provides them you, the developer your users (uploads)
Examples style.css, app.js, logo.svg avatars, attachments
Settings STATIC_URL, STATIC_ROOT, STATICFILES_DIRS MEDIA_URL, MEDIA_ROOT
Model field — FileField, ImageField

Where static files live

Like templates, each app can have its own static/<app>/ folder; project-wide files go in a folder listed in STATICFILES_DIRS:

text
bookshelf/
├── static/                     # project-wide (listed in STATICFILES_DIRS)
│   └── css/
│       └── base.css
└── books/
    └── static/
        └── books/              # app files, namespaced by the app name
            ├── books.css
            └── cover-placeholder.png
python
# settings.py
INSTALLED_APPS = [..., "django.contrib.staticfiles"]

STATIC_URL = "static/"                    # URL prefix for static files
STATICFILES_DIRS = [BASE_DIR / "static"]  # extra folders to search
STATIC_ROOT = BASE_DIR / "staticfiles"    # where collectstatic copies everything (production)

The static template tag

Never hard-code /static/... in templates. Load the static library and let Django build the URL from STATIC_URL — if you later move files to a CDN, only the setting changes:

python · try it yourself
import django
from django.conf import settings
settings.configure(
    INSTALLED_APPS=["django.contrib.staticfiles"],
    STATIC_URL="static/",
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates"}],
)
django.setup()
from django.template import Template, Context

page = Template("""{% load static %}<link rel="stylesheet" href="{% static 'css/base.css' %}">
<img src="{% static 'books/cover-placeholder.png' %}" alt="cover">
{% static 'js/app.js' as app_js %}<script src="{{ app_js }}"></script>""")
print(page.render(Context()))
<link rel="stylesheet" href="/static/css/base.css">
<img src="/static/books/cover-placeholder.png" alt="cover">
<script src="/static/js/app.js"></script>

Changing STATIC_URL changes every link at once — here to a CDN:

python · try it yourself
import django
from django.conf import settings
settings.configure(
    INSTALLED_APPS=["django.contrib.staticfiles"],
    STATIC_URL="https://cdn.example.com/bookshelf/",
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates"}],
)
django.setup()
from django.template import Template, Context
from django.templatetags.static import static

print(Template("{% load static %}{% static 'css/base.css' %}").render(Context()))
print(static("img/logo.svg"))          # the same helper, from Python code
https://cdn.example.com/bookshelf/css/base.css
https://cdn.example.com/bookshelf/img/logo.svg

Serving static files

During development, runserver serves static files automatically when DEBUG = True and django.contrib.staticfiles is installed. Nothing else to do.

In production, Django should not serve static files itself — it's slow at it. Instead you run collectstatic, which copies every app's and every STATICFILES_DIRS file into one folder, STATIC_ROOT:

bash · try it yourself
python manage.py collectstatic
You have requested to collect static files at the destination
location as specified in your settings:

    /srv/bookshelf/staticfiles

This will overwrite existing files!
Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel: yes

128 static files copied to '/srv/bookshelf/staticfiles'.

The 128 files include the admin's own CSS and JavaScript. Then a web server (nginx, Caddy), a CDN, or the popular WhiteNoise package serves that folder:

python
# settings.py with WhiteNoise (pip install whitenoise)
MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",   # right after SecurityMiddleware
    # ...
]
STORAGES = {
    "staticfiles": {"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage"},
}

Cache busting with manifest storage

Browsers cache CSS and JavaScript aggressively. If you change base.css, visitors might keep the old copy for days. Manifest storage solves this by adding a content hash to each file name during collectstatic — base.css becomes base.4f3a9c1e8b2d.css — and the {% static %} tag automatically outputs the hashed name. A new version means a new URL, so caches can never serve stale files.

python
STORAGES = {
    "default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
    "staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage"},
}

Finding where a file comes from

findstatic tells you which folder a static path resolves to — handy when two apps ship a file with the same name (the first app in INSTALLED_APPS wins, which is why you namespace files under static/<app>/):

bash · try it yourself
python manage.py findstatic css/base.css books/books.css
Found 'css/base.css' here:
  /home/linh/bookshelf/static/css/base.css
Found 'books/books.css' here:
  /home/linh/bookshelf/books/static/books/books.css

Media files in a nutshell

User uploads are stored under MEDIA_ROOT and served from MEDIA_URL. A model field records the relative path:

python
# settings.py
MEDIA_URL = "media/"
MEDIA_ROOT = BASE_DIR / "media"

# models.py
class Book(models.Model):
    cover = models.ImageField(upload_to="covers/", blank=True)   # needs Pillow

# template
<img src="{{ book.cover.url }}">

Note: Never trust uploaded files: limit their size and type, and serve them from a separate domain if possible.

Test yourself

What does {% static 'css/base.css' %} output when STATIC_URL = "static/"?

  1. css/base.css
  2. /static/css/base.css
  3. The file's contents
  4. static/css/base.css relative to the page

Which command copies all static files into STATIC_ROOT for production?

  1. runserver
  2. collectstatic
  3. findstatic
  4. migrate

Why put app static files under static/<app_name>/?

  1. Django requires it
  2. To avoid name clashes between apps
  3. It makes files load faster
  4. For the admin only