Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 257
phazei Avatar asked Oct 29 '25 17:10

phazei


1 Answers

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.

like image 83
Games Brainiac Avatar answered Oct 31 '25 07:10

Games Brainiac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!