开发者

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 s开发者_StackOverflow中文版plit this case?
{% endif %}


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


You can create a custom filter:

@register.filter
def is_not_None(val):
    return val is not None

then use it:

{% if x|is_not_None %}
    {% if x %}
        True
    {% else %}
        False
    {% endif %}
{% else %}
    None
{% endif %}

Of course, you could tweak the filter to test whatever condition you like also...


An enhancement of the previous answers could be:

{% if x|yesno:"2,1," %}
   # will enter here if x is True or False, but not None
{% else %}
   # will enter only if x is None
{% endif %}


Create context_processor (or use from the django-misc module misc.context_processors.useful_constants) with True, False, None constants and use {% if x == None %} or {% if x == False %}

context_processor.py:

def useful_constants(request):
    return {'True': True, 'False': False, 'None': None}


Here is another tricky way:

{% if not x.denominator %}
    None
{% else %}
    {% if x %}
        True
    {% else %}
        False
    {% endif %}
{% endif %}

That's because "None" doesn't have the attribute "denominator", while it is 1 for both "True" and "False".

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜