Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

Replace django.core.context_processors.static with django.templatetags.static:

>>> from django.template import Context,Template
>>> from django.template.loader import add_to_builtins
>>> add_to_builtins('django.templatetags.static')
>>> Template('{% static "img/test.jpg" %}').render(Context())
'/static/img/test.jpg'

BTW, your code has a typo: Replace add_to_bultins with add_to_builtins.

The answers are old and don't work in Django 3

in settings.py add 'django.templatetags.static' under TEMPLATES -> OPTIONS -> builtins

so with a basic default setup it should look like:

TEMPLATES = [
    {
        'BACKEND': ...,
        'DIRS': ...,
        'OPTIONS': {
            'context_processors': [
                ...
            ],
            'builtins': [
                'django.templatetags.static',
            ],
        },
    },
]

thanks to a blog: https://chris-lamb.co.uk/posts/importerror-cannot-import-name-add_to_builtins-under-django-19

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top