In old version you can only use the ifequal or ifnotequal
{% ifequal YourVariable ExpectValue %}
# Do something here.
{% endifequal %}
Example:
{% ifequal userid 1 %}
Hello No.1
{% endifequal %}
{% ifnotequal username 'django' %}
You are not django!
{% else %}
Hi django!
{% endifnotequal %}
As in the if tag, an {% else %} clause is optional.
The arguments can be hard-coded strings, so the following is valid:
{% ifequal user.username "adrian" %}
...
{% endifequal %}
An alternative to the ifequal tag is to use the if tag and the == operator.
ifnotequal
Just like ifequal, except it tests that the two arguments are not equal.
An alternative to the ifnotequal tag is to use the if tag and the != operator.
However, now we can use if/else easily
{% if somevar >= 1 %}
{% endif %}
{% if "bc" in "abcdef" %}
This appears since "bc" is a substring of "abcdef"
{% endif %}
Complex expressions
All of the above can be combined to form complex expressions. For such expressions, it can be important to know how the operators are grouped when the expression is evaluated - that is, the precedence rules. The precedence of the operators, from lowest to highest, is as follows:
- or
- and
- not
- in
- ==, !=, <, >, <=, >=
More detail
https://docs.djangoproject.com/en/dev/ref/templates/builtins/
{% if not myvar%}
it works in Django 1.11 for sure, I am not how far back you can go, though! – Preinstructnot myvar
checks if myvar is falsey, notFalse
. see also – Hairpiecemyvar
was a boolean,not myvar
will returnTrue
if it was sent to the template as a context variable by the render function regardless of its value (true or false)? in this case, one should check 2 things: 1-myvar
was provided to the render function, 2-what valuemyvar
has if provided. This will be pretty much complicated ifmyvar
is more of a class instace, dictionary, object etc rather than a classic variable. – Preinstruct