Setting up Django to display the default template tag when the variable is None?

I am looking for a django setting or a programmatic way to make all django template tags display an empty string when the value is None. For example, imagine that I have a django template:

{{cat}} chases {{mouse}} 

If both mice and mice are None, this will look like:

 None chases None 

I know that I can install each of them using {{cat|default:""}} or {{mouse|default_if_none:""}}

However, I am looking for some kind of setting that would allow me to set a default value for all tags without explicitly adding |default:"" to each tag.

I also know a setting called TEMPLATE_STRING_IF_INVALID . However, this option applies only to invalid strings. No is considered valid.

+25
python django django-templates
Sep 28 2018-11-11T00:
source share
3 answers

There is no such thing. This is why there are default and default_if_none filters default_if_none This is a feature; it makes you think about what you are doing, rather than relying on some kind of behavior that is often misleading. If it is likely that the variable will be None , then you should plan for this unforeseen situation. If a variable should always have some value, then โ€œNoโ€ indicates that something is wrong. If by default you just needed to display an empty string, you wonโ€™t know if the value is defined or if it is actually an empty string. Write a coherent code and forget about the shortcuts.

+34
Sep 28 '11 at 10:15
source share

"Explicit is better than implicit"

Think about how furious you would be if things werenโ€™t displaying properly, because you forgot that you turned on the "show all with false value as zero line" option.

If you find that you often use the default_if_none filter, you may need to change the change in None to '' before it is passed to the template.

Your template will be simpler, and you will obviously have this solution generate zero values.

+4
Sep 28 '11 at 22:21
source share

This should do the trick, put it somewhere in the initialization code, for example. in wsgi.py

 # Patch template Variable to output empty string for None values from django.template.base import Variable _resolve_lookup = Variable._resolve_lookup def new_resolve_lookup(self, *args, **kwargs): o = _resolve_lookup(self, *args, **kwargs) return o or u"" Variable._resolve_lookup = new_resolve_lookup 
+3
Jul 20 '12 at 11:50
source share



All Articles