Django Global CSS file
Add a CSS File to the Entire Project
In the previous chapter we learned how to add a .css
file to an application in a project.
But what if you want to use a stylesheet in the entire project?
Well, start by creating a folder on the project's root level,
this folder can be called whatever you like, I will call it
mystaticfiles
in this tutorial:
my_tennis_club
manage.py
my_tennis_club/
members/
mystaticfiles/
Add a file in the mystaticfiles
folder, name it myglobal.css
:
my_tennis_club
manage.py
my_tennis_club/
members/
mystaticfiles/
myglobal.css
Open the CSS file and insert the following:
my_tennis_club/mystaticfiles/myglobal.css
:
body {
color: violet;
}
Modify Settings
You will have to tell Django to also look for static files in the
mystaticfiles
folder in the root directory,
this is done in the settings.py
file:
Add a STATICFILES_DIRS
list:
my_tennis_club/my_tennis_club/settings.py
:
.
.
STATIC_URL = 'static/'
#Add this in your settings.py file:
STATICFILES_DIRS = [
BASE_DIR / "mystaticfiles"
]
.
.
In the STATICFILES_DIRS
list, you can list all the directories where Django should look for static files.
The BASE_DIR
keyword represents the root directory of the project,
and together with the / "mystaticfiles"
, it
means the mystaticfiles
folder in the root
directory.
Modify the Template
The next step is to include the css file in a template:
Open the template.html
template, and add the following:
Example
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>
Run Example »
Use CSS Files From Both Folders
To use CSS files from different folders, we just add include them as stylesheets in HTML, and Django will search the folders you have listed until it finds a match:
Example
my_tennis_club/members/templates/template.html
:
{% load static %}
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="{% static 'myglobal.css' %}">
<link rel="stylesheet" href="{% static 'myfirst.css' %}">
<body>
{% for x in fruits %}
<h1>{{ x }}</h1>
{% endfor %}
</body>
</html>
Run Example »
Search Order
If you have files with the same name, Django will use the first occurrence of the file.
The search starts in the directories listed in STATICFILES_DIRS
, using the order you have provided.
Then, if the file is not found, the search continues in the static
folder of each application.