Static File Settings
Setting STATIC_ROOT
is one of the configurations that can often create an error as the mechanism of statics file handling is often incorrectly understood.
Static file locations
Django is designed to let a web server or a reverse proxy server (e.g., Nginx) handle static files directly in the production environment. By this configuration, the Django app can focus more on the dynamic part.
Development Stage
When DEBUG
is True
, Django considers that the app is running still under the development environment, and the development server (runserver) gets the static files from the original locations. The locations are specified through the STATICFILES_DIRS
settings. You can list multiple locations. Usually, there are two types of locations. One is directly under the project file. The other is under each app directory.
Assuming STATIC_URL = 'static/'
, when an HTTP request with /static/ comes, the development server handles the static files located in the static directories specified by STATICFILES_DIRS.
Production Stage
When DEBUG
is switched to False
, Django considers that the app is running under the production environment and lets the web server (or reverse proxy server) handle the static files stored in the specified location set by STATIC_ROOT
.
Assuming STATIC_URL = 'static/'
is written in the settings.py file, when an HTTP request with /static/
comes, the web server handles the static files located in the static directory specified by STATIC_ROOT
.
collectstatic
The collectstatic
command collects all static files located in several places and puts them in the directory specified by STATIC_ROOT
.
If you don't do this, your web application UI will be broken.
This is an example of the Django admin page when you forget to run the collectstatic
command. We'll demonstrate the command in the next section.
Tips: How to write STATIC_ROOT
For a beginner, writing STATIC_ROOT
can be confusing. As you can set multiple locations for STATICFILES_DIRS
, you should use a list format for it
. However, as STATIC_ROOT
should have only one directory path, you should not use the list format.
Also, the STATIC_ROOT
path should not be the same as the one in STATICFILES_DIRS,
as the static files under STATICFILES_DIRS
will be copied to STATIC_ROOT
by the collectstatic
command. We'll explain how to set STATIC_ROOT
in our app on the next page along with the collectstatic
command.