[Fixed]-Does default_if_none have any use in Django templates?

17👍

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

Consider the following context:

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

In your template {{ apple }} resolves to green, while {{ 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.

👤Wogan

5👍

Here’s a case where I have used default_if_none a few times. I’m querying a secondary database in which I have no control and I’m displaying the data in the template. Most of the times the data looks fine but sometimes, the data value will show None. In that case, I will use the filter as:

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

The general public and users of site doesn’t usually understand what the None value means, by replacing it with a more friendly word, the filter default_if_none comes in handy.

0👍

I have a Django model with a method returning the the number of days a trade has been open (an integer). For the first 24 hours it returns 0. However, once the trade is closed, it returns None.

In this situation, the distinction between default and default_if_none is important… I need to use default_if_none… otherwise, for the first 24 hours a trade is open, it looks as if they were already closed (because zero is falsy).

Leave a comment