Georgy Gritsenko Georgy Gritsenko - 1 year ago 77
Python Question

Django string_if_invalid and default

I have

set to 'INVALID' in my django template settings.
And there is some template that looks like this:

{{ some_nonexisting_value|default:'Default value' }}

After rendering result looks like
. So, default value is not used.
Is there any way to make
to work with default values without changing templates?

Template settings look like this:

'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
'libraries': {
'utm_tags': 'kurator.templatetags.utm_tags',
'string_if_invalid': 'INVALID',
'context_processors': [

Answer Source

No, it's not possible to get the default filter to display the provided default instead of the invalid string.

Note that the docs warn against using the string_if_invalid option:

For debug purposes only!

While string_if_invalid can be a useful debugging tool, it is a bad idea to turn it on as a ‘development default’.

Many templates, including those in the Admin site, rely upon the silence of the template system when a non-existent variable is encountered. If you assign a value other than '' to string_if_invalid, you will experience rendering problems with these templates and sites.

Generally, string_if_invalid should only be enabled in order to debug a specific template problem, then cleared once debugging is complete.

For your own templates, I guess you could write your own template tag that takes the variable name and a default, then tries to fetch the variable from the template context. However, this wouldn't solve the problem in other templates that use the regular default filter, including the Django admin.