When you work with Django and especially with static files or other template tags you realize that you have to include {% load staticfiles %} in all our template files. This violates the DRY principle because we have to repeat the {% load staticfiles %} template tag on each template file .

Lets give an example.

We have a base.html file which links some Javascript and CSS files from our static folder.

{% load staticfiles %}
<!DOCTYPE html>
<html>
    <head>
        <title>Webapp</title>
        <link rel="stylesheet" type="text/css" href="{% static "css/random-css.css" %}">
        <script type="text/javascript" src="{% static "js/random-javascript.js" %}"></script>
        {% block extra_js_top %}{% endblock %}
    </head>
...
</html>

Also we have index.html which extends base.html and in addition it loads some extra javascript.

{% extends "base.html" %}
{% load staticfiles %}
{% block extra_js_top %}
    <script type="text/javascript" src="{% static "js/extra-javascript.js" %}"></script>
{% endblock %}

As you can see I load again staticfiles in index.html. If I remove it, I will take this error. “TemplateSyntaxError at /, Invalid block tag ‘static’”. Unfortunately even if we extend base.html it will not inherit load template tag from the file and it will not load staticfiles to index.html that means it will not load our extra javascript file.
The truth is that there is a hack-y way to do that. After a small research I finally found a way to follow DRY principle and avoid repeating {% load staticfiles %} template tag in every template file.

Open one of the files that loads automatically from the beginning( settings.py, urls.py and models.py ). I will use settings.py.
So we add the following to settings.py:

from django import template
 
#django-staticfiles DRY principle
template.add_to_builtins('django.contrib.staticfiles.templatetags.staticfiles')

With that snippet of code we load statcifiles “globally” and we don’t have to load staticfiles for every template (not even in base.html) because it loads from the beginning.

PS: Sometimes on big projects this way maybe will not be so ‘correct’ or considered unconventional technique and complicate the developers.

I hope it will be useful.

Happy django-ing.

Further reading: