Unlock the power of reusable static files, simplifying your Django development workflow and enhancing your website’s aesthetics.

To begin, establish a static folder in your project in the same location as the templates folder:
The folder must have a static name.
my_tennis_club
manage.py
my_tennis_club/
members/
templates/
static/
You can choose the name of the CSS file you add to the static folder; in this example, we’ll call it myfirst.css.
my_tennis_club
manage.py
my_tennis_club/
members/
templates/
static/
myfirst.css
After opening the CSS file, add the following:
my_tennis_club/members/static/myfirst.css:
body {
background-color: lightblue;
font-family: verdana;
}
Modifying a Template
A CSS file with some CSS style is now in your possession. Adding this file to an HTML template will be the next step:
Add the following after opening the HTML file:
{% load static %}
Additionally:
<link rel="stylesheet" href="{% static 'myfirst.css' %}">
my_tennis_club/members/templates/template.html:
{% load static %}
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="{% static 'myfirst.css' %}">
<body>
{% for x in fruits %}
<h1>{{ x }}</h1>
{% endfor %}
</body>
</html>
The changes will take effect once you restart the server:
py manage.py runserver
Use your own browser to view the outcome: 127.0.0.1:8000/testing/.
If You Encounter Problems
Only a test? Setting DEBUG = True in the settings.py file will allow the aforementioned example to function if you only want to experiment and won’t be deploying your work.
Are you planning to deploy? You should set DEBUG = False in the settings.py file if you intend to deploy your work. Because Django lacks an integrated solution for delivering static files, the aforementioned example will not work. However, there are alternative methods for serving static files, which you will discover in the upcoming chapter.
Example (in development):
my_tennis_club/my_tennis_club/settings.py:
.
.
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
.
.
In order to learn how to work with Django, we want you to select DEBUG = False, however this will make the example work.
Select Debug = False.
We will use DEBUG = False throughout the remainder of this tutorial, even in development, as it is the most effective method for learning how to work with Django.
Example:
my_tennis_club/my_tennis_club/settings.py:
.
.
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
.
.
Installing WhiteNoise in Django
Static file serving is not supported by Django, at least not in production settings where DEBUG must be False. This requires the usage of a third-party solution. The Python package WhiteNoise, designed for providing static files, will be used in this tutorial.
Enter the following command to install WhiteNoise in your virtual environment:
pip install whitenoise
This is the expected outcome:
Collecting whitenoise
Downloading whitenoise-6.2.0-py3-none-any.whl (19 kB)
Installing collected packages: whitenoise
Successfully installed whitenoise-6.2.0
WARNING: You are using pip version 20.2.3; however, version 22.3.1 is available.
You should consider upgrading via the 'c:\users\Your Name\myworld\scripts\python.exe -m pip install --upgrade pip' command.
Configuring Application Settings
In the settings.py file, you must include WhitNoise in the MIDDLEWARE list to inform Django that you wish to run it:
my_tennis_club/my_tennis_club/settings.py:
.
.
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',
'whitenoise.middleware.WhiteNoiseMiddleware',
].
Managing Static Files
Django does not automatically handle static files in your project, such as stylesheets, JavaScripts, and pictures, when DEBUG = False.
This functioned perfectly with DEBUG = True; all we needed to do was place them in the application’s static folder.
Before we can use it, static files must be gathered and placed in a designated location when DEBUG = False.
Gather Static Documents
Setting a STATIC_ROOT option in the settings.py file is the first step in gathering all the static files required for your project.
This indicates the folder in which you choose to store your static files.
We’ll call the folder productionfiles, but you can call it anything you want:
my_tennis_club/my_tennis_club/settings.py:
.
.
STATIC_ROOT = BASE_DIR / 'productionfiles'
STATIC_URL = 'static/'
Django includes a script that does this for you, but you could also manually create this folder and gather and place all of your project’s static files inside it:
py manage.py collectstatic
It will bring about this outcome:
131 static files copied to 'C:\Users\your_name\myworld\my_tennis_club\productionfiles'.
A total of 131 files? How come there are so many? This, however, is due to the admin user interface that is included with Django. Stylesheets, fonts, pictures, and JavaScripts are among the many assets that come with this functionality, which we wish to maintain in production.
my_tennis_club
members/
my_tennis_club/
productionfiles/
admin/
myfirst.css
It Should Work as an Example
After gathering your project’s static files, the Add Static Files chapter example will finally function if WhiteNoise has been installed.
Launch the server to observe the outcome:
py manage.py runserver
Use your own browser to view the outcome: 127.0.0.1:8000/testing/.
Example
my_tennis_club/members/templates/template.html:
{% load static %}
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="{% static 'myfirst.css' %}">
<body>
{% for x in fruits %}
<h1>{{ x }}</h1>
{% endfor %}
</body>
</html>
Managing Global Static Files in Django
We now know how to utilize a static file in the program and how to add it to the static folder.
However, what if the file is needed by other apps in your project?
The next step is to make a folder in the root directory and place the file or files inside.
Making a static folder in the root directory is insufficient; Django will take care of the rest. Django needs to know where to find these static files.
To begin, create a folder at the root level of the project. You may call this folder anything you like, but for the purposes of this tutorial, I’ll call it mystaticfiles:
my_tennis_club
db.sqlite3
manage.py
my_tennis_club/
members/
mystaticfiles/
You may choose the name of the CSS file you add to the mystaticfiles folder; in this example, we’ll call it myglobal.css.
my_tennis_club
db.sqlite3
manage.py
my_tennis_club/
members/
mystaticfiles/
myglobal.css
After opening the CSS file, add the following:
my_tennis_club/mystaticfiles/myglobal.css:
body {
color: violet;
}
Changing Application Settings
In the settings.py file, you must instruct Django to search the root directory’s mystaticfiles folder for static files as well.
Add a STATICFILES_DIRS list:
my_tennis_club/my_tennis_club/settings.py:
.
.
STATIC_ROOT = BASE_DIR / 'productionfiles'
STATIC_URL = 'static/'
#Add this in your settings.py file:
STATICFILES_DIRS = [
BASE_DIR / 'mystaticfiles'
]
All of the folders where Django should search for static files are listed in the STATICFILES_DIRS list.
In conjunction with the / "mystaticfiles"
suffix, the BASE_DIR keyword denotes the project’s root directory and the mystaticfiles folder within it.
Modifying a Template
The whole project is now included in a global CSS file that is accessible from every program you use.
The syntax for using it in a template is the same as that used for the myfirst.css file:
Start the template by entering the following:
{% load static %}
And make use of the file as follows:
<link rel="stylesheet" href="{% static 'myglobal.css' %}">
Exampe
my_tennis_club/members/templates/template.html:
{% load static %}
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="{% static 'myglobal.css' %}">
<body>
{% for x in fruits %}
<h1>{{ x }}</h1>
{% endfor %}
</body>
</html>
Gather Static Files
To gather the new static file, use the collectstatic command:
py manage.py collectstatic
This will result in this outcome:
You have requested to collect static files at the destination
location as specified in your settings:
C:\Users\Your Name\myworld\my_tennis_club\productionfiles
This will overwrite existing files!
Are you sure you want to do this?
Type 'yes' to continue, or 'no' to cancel:
Enter yes:
Type 'yes' to continue, or 'no' to cancel: yes
This will result in this outcome:
1 static file copied to 'C:\Users\Your Name\myworld\my_tennis_club\productionfiles', 131 unmodified.
The Example Should Function Correctly
Once the server is started, the example will function:
py manage.py runserver
Check out the result in your own browser: 127.0.0.1:8000/testing/.
my_tennis_club/members/templates/template.html:
{% load static %}
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="{% static 'myglobal.css' %}">
<body>
{% for x in fruits %}
<h1>{{ x }}</h1>
{% endfor %}
</body>
</html>