Menu
CoddyTech

Static Files for Production

Part of the JSON APIs section of Coddy's Django journey. Lesson 19 of 19.

In production a program like Gunicorn runs Django instead of runserver, and it does not serve static files such as app.js. They are served from one folder, by the web server or a package like WhiteNoise.

That folder is STATIC_ROOT, an absolute path. python manage.py collectstatic copies every app's static/ files into it, and you run it on every deploy. Without STATIC_ROOT it stops with ImproperlyConfigured.

Paths in settings are built from BASE_DIR, the folder that holds manage.py, with the / operator of pathlib. The folder for files that visitors upload:

MEDIA_ROOT = BASE_DIR / "uploads"

Before going live, python manage.py check --deploy lists settings that are not ready.

challenge icon

Challenge

Easy

In mysite/settings.py, under STATIC_URL, set STATIC_ROOT to the folder staticfiles next to manage.py, as an absolute path.

Press Run, then in the Shell tab: from django.core.management import call_command; call_command("collectstatic", interactive=False) prints how many files it copied.

Try it yourself

import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY", "django-insecure-change-me")
DEBUG = os.environ.get("DJANGO_DEBUG", "False") == "True"
ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS", "localhost,127.0.0.1").split(",")

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "tasks",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "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",
]

ROOT_URLCONF = "mysite.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db.sqlite3",
    }
}

LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True

STATIC_URL = "static/"
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in JSON APIs

Practice on your own: Django playground