liveBook · Manning

Static template tag

As explained in Django in Action

The Django static template tag generates or resolves the URL of a static file using the configured static-file settings.

The Django static template tag generates a URL for a static file such as an image, stylesheet, or JavaScript file. Because a file’s URL and filesystem location can differ between environments, the tag uses Django’s static-file configuration instead of hard-coding a path. section 7.3 section 7.6

Use the tag with these conventions:

  • Load it with `{% load static %}` unless the static tag library has been added to the template builtins. section 7.3
  • Pass a path relative to the static directory, such as `img/logo.png`. section 7.3
  • Place the resulting URL inside HTML attributes such as `<img src="...">` or `<link href="...">`. section 7.3
  • Configure the project’s static directory through `STATIC_URL` and `STATICFILES_DIRS`; production deployment may require additional steps. section 7.3

A RiffMates logo

Store the logo at `RiffMates/static/img/logo.png`, configure the project’s `static` directory, and use `{% load static %}` followed by `<img src="{% static 'img/logo.png' %}" height="100">` in `home.html`. Django resolves the configured static URL while the template supplies the file’s relative name. section 7.3

Listing 7.13 Template for the home page that includes a static file
<!-- RiffMates/templates/home.html -->
{% extends "base.html" %}
{% load static %}  #1

{% block content %}
  <img src="{% static 'img/logo.png' %}" height="100">  #2
  <h1>Welcome to RiffMates!</h1>

  <ul>  #3
    <li> <a href="{% url 'news' %}">News</a> </li>
    <li> <a href="{% url 'musicians' %}">Musicians</a> </li>
    <li> <a href="{% url 'bands' %}">Bands</a> </li>
    <li> <a href="{% url 'venues' %}">Venues</a> </li>
    <li> <a href="{% url 'list_ads' %}">Classified Ads</a> </li>
    <li> <a href="{% url 'comment' %}">Leave a comment</a> </li>
  </ul>

{% endblock content %}

Inspect the complete home-page template to see the static tag alongside template inheritance and URL tags. section 7.3

How Django in Action covers it

How deep it goes
Explains loading, configuration, relative paths, and HTML use, while deferring further production-serving steps.
Examples
Uses a RiffMates logo, `home.html`, `STATIC_URL`, and `STATICFILES_DIRS` as concrete artifacts.
What it assumes
Assumes basic Django templates and HTML, while teaching static directories, tag loading, and static-file configuration.
What you can do after
Apply it via Django templates to reference static assets without hard-coding deployment-specific URLs.
How it connects
Connects template tags with Django settings, static files, HTML, and web-server serving.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.