Search code examples
djangopython-2.7django-templatesdjango-staticfilesdjango-1.4

Load Django "static" template tag library globally without explicitly loading it in every file


I want to use the static tag in templates like so:

<img src="{% static "img/test.jpg" %}">

I've found that that requires me to put

{% load static %}

at the beginning of every template file. Since I'm using it everywhere, I would like it to be a globally available tag so I don't need to put {% load static %} to use it.

In my settings I do have:

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.static',
)

I saw both of these questions: Make django static tag globally available and Load a Django template tag library for all views by default though neither seems to answer the question. In the former the question wasn't clear and in the later I get errors when I try to use:

from django.template.loader import add_to_builtins
add_to_builtins('django.core.context_processors.static')

Perhaps I'm not putting it in the correct location, or perhaps it's already part of the core so doesn't work?

How can I automatically get the static tag added into all template files without explicitly loading it for every file?


Solution

  • I think a lot of answers forget where you need to put the code. Well, let me start by telling you that you can use the following code to get the job done:

    from django.template.loader import add_to_builtins
    add_to_builtins('django.templatetags.static')
    

    Now put this, in your main urls.py file. This worked for me.