Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django templates: False vs. None

How can I distinguish between None and False in django templates?

{% if x %}
True 
{% else %}
None and False - how can I split this case?
{% endif %}
like image 358
Evg Avatar asked Jul 15 '10 19:07

Evg


People also ask

What does {% %} mean in Django?

The {% if %} tag evaluates a variable, and if that variable is “true” (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output. One can use various boolean operators with Django If Template tag.

How do you solve template does not exist in Django?

Django TemplateDoesNotExist error means simply that the framework can't find the template file. To use the template-loading API, you'll need to tell the framework where you store your templates. The place to do this is in your settings file ( settings.py ) by TEMPLATE_DIRS setting.

What is Forloop counter in Django?

A for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.

Which is a nonstandard place to store templates Django?

To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.


1 Answers

Every Django template context contains True, False and None. For Django 1.10 and later, you can do the following:

{% if x %}
True 
{% elif x is None %}
None
{% else %}
False (or empty string, empty list etc)
{% endif %}

Django 1.9 and earlier do not support the is operator in the if tag. Most of the time, it is ok to use {% if x == None %} instead.

{% if x %}
True 
{% elif x == None %}
None
{% else %}
False (or empty string, empty list etc)
{% endif %}

With Django 1.4 and earlier, you do not have access to True, False and None in the template context, You can use the yesno filter instead.

In the view:

x = True
y = False
z = None

In the template:

{{ x|yesno:"true,false,none" }}
{{ y|yesno:"true,false,none" }}    
{{ z|yesno:"true,false,none" }}    

Result:

true
false
none
like image 134
Alasdair Avatar answered Sep 19 '22 17:09

Alasdair