Georgy Gritsenko Georgy Gritsenko - 25 days ago 11
Python Question

Django string_if_invalid and default

I have

string_if_invalid
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
'INVALID'
. So, default value is not used.
Is there any way to make
string_if_invalid
to work with default values without changing templates?

Edit:
Template settings look like this:

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
'OPTIONS': {
'libraries': {
'utm_tags': 'kurator.templatetags.utm_tags',
},
'string_if_invalid': 'INVALID',
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'kurator.context_processors.static_hash',
'kurator.context_processors.debug',
]
},
},
]

Answer

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.