🎓 A1Learner
🔍
0 of 50 lessons completed

Linking Django Static Files

The static template tag makes the address of a static file. The tag reads the file name and adds the prefix.

Write a CSS file

This code puts style.css into the static folder.

os.makedirs(BASE_DIR / "static", exist_ok=True)
(BASE_DIR / "static" / "style.css").write_text("h1 { color: blue; }")

The template link

The load line makes the static tag ready. The tag builds the address from the file name.

{% load static %}
<link href="{% static "style.css" %}">

Build the link

The template renders the link tag. The print shows the built address.

template = Template('{% load static %}<link href="{% static "style.css" %}">')
print(template.render(Context()))

Example

import django
from django.conf import settings

settings.configure(
    DEBUG=True,
    SECRET_KEY="key",
    ROOT_URLCONF=__name__,
    ALLOWED_HOSTS=["*"],
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True}],
    STATIC_URL="/static/",
)
django.setup()

import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent
os.makedirs(BASE_DIR / "static", exist_ok=True)
(BASE_DIR / "static" / "style.css").write_text("h1 { color: blue; }")

from django.template import Context, Template

template = Template('{% load static %}<link href="{% static "style.css" %}">')
print(template.render(Context()))

Key points

  • {% load static %} loads the static tag.
  • {% static "style.css" %} builds the file address.
  • The address starts with /static/.
  • Build static links with the tag, never by hand.
  • The file name is the path inside the static folder.

In this example, the setup lines configure Django. The program writes style.css into the static folder first. The template loads the static tag and builds the link address from the file name. The print shows the link with the /static/style.css address in it.

Note

The load line must come before the tag is used.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does {% static "style.css" %} give back?