Django - Add Static File
Create Static Folder
When building web applications, you probably want to add some static files like images or css files.
Start by creating a folder named static
in your project, the same place where you created the templates
folder:
my_tennis_club
manage.py
my_tennis_club/
members/
templates/
static/
Add a file in the static
folder, name it myfirst.css
:
my_tennis_club
manage.py
my_tennis_club/
members/
templates/
static/
myfirst.css
Open the CSS file and insert the following:
my_tennis_club/members/static/myfirst.css
:
body {
background-color: lightblue;
font-family: verdana;
}
Modify the Template
Now you have a css file, with some css properties that will style HTML elements. The next step will be to include this file in a HTML template:
Open the HTML file and add the following:
{% load static %}
And:
<link rel="stylesheet" href="{% static 'myfirst.css' %}">
Restart the server for the changes to take effect:
py manage.py runserver
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>
Run Example »
Didn't Work?
In development: If you just want to play around, and not
going to deploy your work, you can set DEBUG = True
in the settings.py
file,
and the static files will work.
In production If you plan to deploy your work, you should
set DEBUG = False
in the settings.py
file. Then
the example above will fail because Django has no built-in solution for this.
But there are several other ways to serve static files in production. You will
learn how in the next 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
.
.
Example (in production):
my_tennis_club/my_tennis_club/settings.py
:
.
.
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1','yourdomain']
.
.
ALLOWED_HOSTS
When using DEBUG = False
you have to specify the which host name(s) are allowed
to host your work, and we specify '127.0.0.1'
which normally is the address of your local machine.
The other address is the host name after you have deployed.
If you do not have any host name yet, you can use ALLOWED_HOSTS = ['*']
, which means that you allow any host name. Just make sure you change this to
a real domain name when you get one.
Serving Static Files
Setting DEBUG = False
and
ALLOWED_HOSTS = ['*']
is not enough!
You will have to make some other changes to get the example above to work.
There are many alternative solutions on how to serve static files, one of them is using WhiteNoise, which you will learn about in the next chapter.