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 file:
    • Make sure that django.contrib.staticfiles is included in INSTALLED_APPS.
    • If it doesn’t already exist, define STATIC_URL. This is where django looks for static files. For example:
STATIC_URL = '/static/'
  • Make a folder called static in your app folder and put styles.css there. Inside this folder you can organize the structure however you want. For example you could create a css 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:

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}">
  • Start (or restart) the server:
$ python runserver

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!

Subscribe via RSS