开发者

Does default_if_none have any use in Django templates?

From the Django docs,

Generally, if a variable doesn't exist, the template system inserts the value of the TEMPLATE_STRING_IF_INVALID setting, which is set to '' (the empty string) by default.

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

This behavior is slightly different for the if, for and regroup template tags. If an invalid variable is provided to one of these template tags, the variable will be interpreted as None. Filters are always开发者_开发技巧 applied to invalid variables within these template tags.

If an invalid variable always gets translated to '', for template tags and filters other than if, for and regroup, then what good does the template filter default_if_none do? Obsolete?


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.


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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜