Django pattern if condition

asked a question here.

I have the following

{% if form.tpl.yes_no_required == True %} <!-- path 1 --> {% else %} {% if form.tpl.yes_no_required == False %} <!-- path 2 --> {% endif %} {% endif %} 

The value for form.tpl.yes_no_required is None, but I was redirected to path 2. Can someone explain why this is so? EDIT: if the value is none, I don't want it to display anything.

+6
source share
2 answers

You cannot use the template language to verify what you think are constants; the parser actually tests 2 "literals".

The analyzer analyzes 2 literals with the names "No" and "False". When the parser tries to resolve them in context, a VariableDoesNotExist exception is thrown and both objects are resolved with the value python None and None == None.

 from django.template import Context, Template t = Template("{% if None == False %} not what you think {% endif %}") c = Context({"foo": foo() }) 

prints u 'not what you think'

 c = Context({'None':None}) t.render(c) 

prints u 'not what you think'

 c = Context({'None':None, 'False':False}) t.render(c) 

prints u ''

+14
source

No! = False No! = True also ... do some things like this for none

 {% if form.tpl.yes_no_required %} <!-- path 1 --> {% else %} {% if not form.tpl.yes_no_required %} <!-- path 2 --> {% endif %} {% endif %} 
+1
source

Source: https://habr.com/ru/post/885927/


All Articles