Including static files in Django templates
Dealing with static files in django can be confusing. In this guide you’ll learn how to include any type of static file (CSS, javascript, images, etc) in your templates during development.
Let’s say you have a file called styles.css
and you want to include it in your templates.
- Open your
settings.py
file:- Make sure that
django.contrib.staticfiles
is included inINSTALLED_APPS
. - If it doesn’t already exist, define
STATIC_URL
. This is where django looks for static files. For example:
- Make sure that
-
Make a folder called
static
in your app folder and putstyles.css
there. Inside this folder you can organize the structure however you want. For example you could create acss
folder to contain all your styling:myapp/static/css/styles.css
-
Now you can head over to your templates, wherever you want to include the CSS file, and add these tags:
- Start (or restart) the server:
If you open the HTML source in your browser, you will see that django has automatically expanded the {% static %}
template tag and has generated the absolut URL fo the static file.
This is all you need to do to serve static files during development. Production is a slightly different story. But you don’t need to worry about that for now!