🎓 A1Learner
🔍
0 of 50 lessons completed

The Django Static Folder

The static folder holds files Django serves unchanged. CSS files and images live there.

Write a static file

This code puts hello.txt into the static folder.

os.makedirs(BASE_DIR / "static", exist_ok=True)
(BASE_DIR / "static" / "hello.txt").write_text("Hello from a static file")

The setting

STATIC_URL sets the address prefix. STATICFILES_DIRS lists the folders Django searches.

STATIC_URL = "/static/"
STATICFILES_DIRS = [BASE_DIR / "static"]

Find the file

finders.find looks for a file in the static folders. It gives back the file path.

from django.contrib.staticfiles import finders

print(os.path.basename(finders.find("hello.txt")))

Example

import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent
os.makedirs(BASE_DIR / "static", exist_ok=True)
(BASE_DIR / "static" / "hello.txt").write_text("Hello from a static file")

import django
from django.conf import settings

settings.configure(
    DEBUG=True,
    SECRET_KEY="key",
    ROOT_URLCONF=__name__,
    ALLOWED_HOSTS=["*"],
    INSTALLED_APPS=["django.contrib.staticfiles"],
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True}],
    STATIC_URL="/static/",
    STATICFILES_DIRS=[BASE_DIR / "static"],
)
django.setup()

from django.contrib.staticfiles import finders

print(settings.STATIC_URL)
print(os.path.basename(finders.find("hello.txt")))

Key points

  • Static files live in the folder named static.
  • Django serves them at /static/ addresses.
  • The file content arrives unchanged.
  • STATIC_URL sets the address prefix for static files.
  • Pages belong in templates, and files belong in static.
  • The static folder is the home for files served as they are.

In this example, the setup lines configure Django. The program writes hello.txt into the static folder first. STATIC_URL sets the address prefix to /static/. STATICFILES_DIRS points at the static folder. The prints show the address prefix and the found file name.

Note

Django serves static files only from folders it knows about.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Where do static files live in a Django project?