Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load static files for all templates in django

Is there a way in django to not need the {% load static %} at the top of every template?

This question indicates you can factor out common load tags into settings, but doesn't give the particulars you need in this case.

like image 940
Zags Avatar asked Mar 07 '16 06:03

Zags


People also ask

What is {% load static %} in Django?

The {% static %} template tag generates the absolute URL of static files. That's all you need to do for development. Reload http://localhost:8000/polls/ and you should see that the question links are green (Django style!) which means that your stylesheet was properly loaded.

How does Django serve static files?

django. contrib. staticfiles provides a convenience management command for gathering static files in a single directory so you can serve them easily. This will copy all files from your static folders into the STATIC_ROOT directory.


2 Answers

As of Django 1.9, you can add a builtins key to your TEMPLATES["OPTIONS"] in settings.py.

For Django 2.1+, use:

'builtins': ['django.templatetags.static']

For Django 1.9 - 2.0 (this will work up until 2.2, after which it is deprecated), use:

'builtins': ['django.contrib.staticfiles.templatetags.staticfiles']

For example, the whole template setting might look like this:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
            'builtins': ['django.templatetags.static'],
        },
    },
]

Thanks to @ZachPlachue for the Django 3 update.

like image 168
Zags Avatar answered Oct 24 '22 19:10

Zags


The previous answer's method is deprecated as of Django 3.0. (see : https://docs.djangoproject.com/en/3.0/releases/3.0/#features-removed-in-3-0)

Now you'd need to add the following to your template settings:

'builtins': ['django.templatetags.static']

This is the updated templates setting:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
            'builtins': [
                'django.templatetags.static',
            ],
        },
    },
]
like image 32
Zack Plauché Avatar answered Oct 24 '22 21:10

Zack Plauché