Is default_if_none used in Django templates?

In Django Docs

Typically, if the variable does not exist, the template system inserts the value TEMPLATE_STRING_IF_INVALID, which is set to '' (empty string) by default.

Filters that apply to an invalid variable will only be applied if TEMPLATE_STRING_IF_INVALID is set to '' (empty string). If TEMPLATE_STRING_IF_INVALID is set to any other value, variable filters will ignore.

This behavior is slightly different for the if, for, and regroup tags. If an invalid variable is provided with tags from one of these templates, the variable will be interpreted as None. Filters are always applied to invalid variables in these template tags.

If an invalid variable always translates to ``, for template tags and filters other than if, for, and rearrangement, then what does the default_if_none template filter do? Outdated?

+7
source share
2 answers

There is a difference between an invalid variable and one that exists but has the value None .

Consider the following context:

 {'apple':'green','banana':None}` 

Your template {{ apple }} resolves to green , and {{ banana }} resolves to None , and {{ orange }} resolves to TEMPLATE_STRING_IF_INVALID .

Now consider {{ banana|default_if_none:'yellow' }} and you should see the use of the default_if_none tag.

+11
source

Here is the case where I used default_if_none several times. I request a secondary database in which I have no control, and I display the data in a template. In most cases, the data looks normal, but sometimes the value of the data will show None . In this case, I will use a filter like:

 {{ data_value|default_if_none:"N/A" }} 

General publication and site users usually do not understand what the value None means, replacing it with a friendlier word, the default_if_none filter is useful.

+3
source

All Articles