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
