Static Files

Serve CSS, JavaScript and images with the static files system.

Syntax{% static 'app/file.css' %}

CSS, JavaScript and images are static files. Put them in a static/ folder inside your app, then load them in templates with the {% static %} tag after {% load static %}.

In development Django serves them automatically. In production you collect them with collectstatic (see Deployment).

Example

Example · python
{% load static %}
<link rel="stylesheet" href="{% static 'blog/style.css' %}">
<img src="{% static 'blog/logo.png' %}" alt="Logo">

<!-- Django resolves these to /static/blog/... -->

When to use it

  • A developer serves a site-wide CSS file and logo image through Django's static file system during development.
  • A team runs collectstatic before deployment to copy all app static files into a single directory for Nginx to serve.
  • A developer uses the {% static %} tag to generate correct URLs for CSS and JS files linked in base.html.

More examples

Configure static files in settings

Sets up the URL prefix, source directories, and collection target for static files.

Example · python
# settings.py
STATIC_URL = "/static/"
STATICFILES_DIRS = [BASE_DIR / "static"]
STATIC_ROOT = BASE_DIR / "staticfiles"  # for collectstatic

Link CSS in a template

Uses the {% static %} template tag to generate the correct URL for a CSS file.

Example · html
{% load static %}
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>...</body>
</html>

Collect static files for production

Runs collectstatic to gather all static files into STATIC_ROOT ready for Nginx or a CDN.

Example · bash
python manage.py collectstatic --noinput
# Copies all static files to STATIC_ROOT for web server

Discussion

  • Be the first to comment on this lesson.