Logical logic in the Django template system

If you set the context variable (e.g. 'woot') as None or just leave it undefined ....

{% if woot%} Yes! {% endif%}

Is there something you expect (nothing). But if you do this:

{% if woot == True%} Yes! {% endif%}

He will print "Yes!" although woot is None / undefined. It seems very unintuitive. Obviously, I can get around this ... but I would like to understand the root cause. Any ideas why this is happening ....?

Evidence:

from django.template import Context, Template x = Template("{% if woot %}Yeah!{% endif %}") y = Template("{% if woot == True %}Yeah!{% endif %}") x.render( Context( {} )) # => u'' y.render( Context( {} )) # => u'Yeah!' x.render( Context( {'woot':None} )) # => u'' y.render( Context( {'woot':None} )) # => u'Yeah!' 

This is on Django 1.4.3

+4
source share
1 answer

In Django 1.5 ( release notes ), the template engine interprets True , False and None as the corresponding Python objects, so {% if woot == True %} will be evaluated to False .

In earlier versions of Django, the woot and True variables are not present in the template context. The expression None == None evaluates to True , so yes! is displayed

+5
source

All Articles