Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django templates: If false?

How do I check if a variable is False using Django template syntax?

{% if myvar == False %} 

Doesn't seem to work.

Note that I very specifically want to check if it has the Python value False. This variable could be an empty array too, which is not what I want to check for.

like image 619
mpen Avatar asked Nov 19 '10 21:11

mpen


People also ask

How do you do if statements in Django?

How to use if statement in Django template. In a Django template, you have to close the if template tag. You can write the condition in an if template tag. Inside the block, you can write the statements or the HTML code that you want to render if the condition returns a True value.

What is Forloop counter in Django?

Django for loop counter All the variables related to the counter are listed below. forloop. counter: By using this, the iteration of the loop starts from index 1. forloop. counter0: By using this, the iteration of the loop starts from index 0.

Which characters are illegal in template variable name in Django?

Variable names consist of any combination of alphanumeric characters and the underscore ( "_" ) but may not start with an underscore, and may not be a number.


1 Answers

For posterity, I have a few NullBooleanFields and here's what I do:

To check if it's True:

{% if variable %}True{% endif %} 

To check if it's False (note this works because there's only 3 values -- True/False/None):

{% if variable != None %}False{% endif %} 

To check if it's None:

{% if variable == None %}None{% endif %} 

I'm not sure why, but I can't do variable == False, but I can do variable == None.

like image 176
Bialecki Avatar answered Sep 29 '22 05:09

Bialecki