Styling Pages with Django
Styling a page means linking a CSS file in the page. The link tag points at the file in the static folder.
Write the CSS file
This code writes a blue heading rule into style.css.
os.makedirs(BASE_DIR / "static", exist_ok=True)
(BASE_DIR / "static" / "style.css").write_text("h1 { color: blue; }")The page template
The template links the CSS file and shows a heading. The static tag builds the href.
{% load static %}
<link rel="stylesheet" href="{% static "style.css" %}">
<h1>Hi</h1>The view renders the page
The view renders the template string. The template language fills in the static address.
def home(request):
template = Template('{% load static %}<link rel="stylesheet" href="{% static "style.css" %}"><h1>Hi</h1>')
return HttpResponse(template.render(Context()))Ask for the page
The test client asks for the home page. The print shows the link tag and the heading.
client = Client()
print(client.get("/").content.decode())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.http import HttpResponse
from django.template import Context, Template
from django.urls import path
from django.test import Client
def home(request):
template = Template('{% load static %}<link rel="stylesheet" href="{% static "style.css" %}"><h1>Hi</h1>')
return HttpResponse(template.render(Context()))
urlpatterns = [path("", home)]
client = Client()
print(client.get("/").content.decode())Key points
- A link tag joins a CSS file to a page.
- The href carries the address of the CSS file.
- The static tag builds the href from the static folder.
- The CSS file sits in static, not in templates.
- The page HTML carries the link tag.
In this example, the setup lines configure Django. The program writes style.css into the static folder first. The home view renders a template with a link tag. The static tag builds the href from the file name. The test client asks for the home page. The print shows the link tag with the /static/style.css address and the heading.
Note
The CSS file itself stays plain text in the static folder.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Where does the href of a page stylesheet point?