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:
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# 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:
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:
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 codehttps://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:
python manage.py collectstaticYou 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:
# 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.
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>/):
python manage.py findstatic css/base.css books/books.cssFound '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:
# 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/"?
- css/base.css
- /static/css/base.css
- The file's contents
- static/css/base.css relative to the page
Which command copies all static files into STATIC_ROOT for production?
- runserver
- collectstatic
- findstatic
- migrate
Why put app static files under static/<app_name>/?
- Django requires it
- To avoid name clashes between apps
- It makes files load faster
- For the admin only