44👍
Django 1.10 (release notes) added the is
and is not
comparison operators to the if
tag. This change makes identity testing in a template pretty straightforward.
In[2]: from django.template import Context, Template
In[3]: context = Context({"somevar": False, "zero": 0})
In[4]: compare_false = Template("{% if somevar is False %}is false{% endif %}")
In[5]: compare_false.render(context)
Out[5]: u'is false'
In[6]: compare_zero = Template("{% if zero is not False %}not false{% endif %}")
In[7]: compare_zero.render(context)
Out[7]: u'not false'
If You are using an older Django then as of version 1.5 (release notes) the template engine interprets True
, False
and None
as the corresponding Python objects.
In[2]: from django.template import Context, Template
In[3]: context = Context({"is_true": True, "is_false": False,
"is_none": None, "zero": 0})
In[4]: compare_true = Template("{% if is_true == True %}true{% endif %}")
In[5]: compare_true.render(context)
Out[5]: u'true'
In[6]: compare_false = Template("{% if is_false == False %}false{% endif %}")
In[7]: compare_false.render(context)
Out[7]: u'false'
In[8]: compare_none = Template("{% if is_none == None %}none{% endif %}")
In[9]: compare_none.render(context)
Out[9]: u'none'
Although it does not work the way one might expect.
In[10]: compare_zero = Template("{% if zero == False %}0 == False{% endif %}")
In[11]: compare_zero.render(context)
Out[11]: u'0 == False'
51👍
For posterity, I have a few NullBooleanField
s 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
.
- [Django]-Django: import auth user to the model
- [Django]-Best way to integrate SqlAlchemy into a Django project
- [Django]-How to delete a record in Django models?
- [Django]-Creating email templates with Django
- [Django]-Tying in to Django Admin's Model History
- [Django]-How can I run a celery periodic task from the shell manually?
23👍
You could write a custom template filter to do this in a half-dozen lines of code:
from django.template import Library
register = Library()
@register.filter
def is_false(arg):
return arg is False
Then in your template:
{% if myvar|is_false %}...{% endif %}
Of course, you could make that template tag much more generic… but this suits your needs specifically 😉
- [Django]-Django error message "Add a related_name argument to the definition"
- [Django]-Consolidating multiple post_save signals with one receiver
- [Django]-Extend base.html problem
10👍
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/
- [Django]-Django Multiple Authentication Backend for one project
- [Django]-Homepage login form Django
- [Django]-URL-parameters and logic in Django class-based views (TemplateView)
6👍
Just ran into this again (certain I had before and came up with a less-than-satisfying solution).
For a tri-state boolean semantic (for example, using models.NullBooleanField
), this works well:
{% if test.passed|lower == 'false' %} ... {% endif %}
Or if you prefer getting excited over the whole thing…
{% if test.passed|upper == 'FALSE' %} ... {% endif %}
Either way, this handles the special condition where you don’t care about the None
(evaluating to False in the if block) or True
case.
- [Django]-In Django 1.4, do Form.has_changed() and Form.changed_data, which are undocumented, work as expected?
- [Django]-Django: How can I create a multiple select form?
- [Django]-Dynamically adding a form to a Django formset
4👍
I have had this issue before, which I solved by nested if statements first checking for none type separately.
{% if object.some_bool == None %}Empty
{% else %}{% if not object.some_bool %}False{% else %}True{% endif %}{% endif %}
If you only want to test if its false, then just
{% if some_bool == None %}{% else %}{% if not some_bool %}False{% endif %}{% endif %}
EDIT: This seems to work.
{% if 0 == a|length %}Zero-length array{% else %}{% if a == None %}None type{% else %}{% if not a %}False type{% else %}True-type {% endif %}{% endif %}{% endif %}
Now zero-length arrays are recognized as such; None types as None types; falses as False; Trues as trues; strings/arrays above length 0 as true.
You could also include in the Context a variable false_list = [False,] and then do
{% if some_bool in false_list %}False {% endif %}
- [Django]-Django: Get model from string?
- [Django]-Suddenly when running tests I get "TypeError: 'NoneType' object is not iterable
- [Django]-Creating my own context processor in django
- [Django]-How do you serialize a model instance in Django?
- [Django]-How to allow users to change their own passwords in Django?
- [Django]-How to get username from Django Rest Framework JWT token
3👍
I’ve just come up with the following which is looking good in Django 1.8
Try this instead of value is not False:
if value|stringformat:'r' != 'False'
Try this instead of value is True:
if value|stringformat:'r' == 'True'
unless you’ve been really messing with repr methods to make value look like a boolean I reckon this should give you a firm enough assurance that value is True or False.
- [Django]-Tailwindcss: fixed/sticky footer on the bottom
- [Django]-What is the Simplest Possible Payment Gateway to Implement? (using Django)
- [Django]-Python 3 list(dictionary.keys()) raises error. What am I doing wrong?
2👍
This is far easier to check in Python (i.e. your view code) than in the template, because the Python code is simply:
myvar is False
Illustrating:
>>> False is False
True
>>> None is False
False
>>> [] is False
False
The problem at the template level is that the template if
doesn’t parse is
(though it does parse in
). Also, if you don’t mind it, you could try to patch support for is
into the template engine; base it on the code for ==
.
- [Django]-UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 2: ordinal not in range(128)
- [Django]-Why is assertDictEqual needed if dicts can be compared by `==`?
- [Django]-How to expire session due to inactivity in Django?
1👍
you can use the int value of true and false
True = any int
False = zero
so, if we take an example:
{% if user.is_authenticated == 1 %}
do something
{% endif %}
this mean in python
if user.is_authenticated:
#do something
and
{% if user.is_authenticated == 0 %}
do something
{% endif %}
this mean in python
if not user.is_authenticated :
#do something
OR equal
if !(user.is_authenticated) :
#do something
OR equal
if user.is_authenticated == False :
#do something
- [Django]-What is actually assertEquals in Python?
- [Django]-In django do models have a default timestamp field?
- [Django]-What is the benefit of using a HyperlinkedModelSerializer in DRF?
0👍
It can be done:if you use "select" tag.
{% if service.active == 0 %} selected {% endif%}
- [Django]-Passing variable urlname to url tag in django template
- [Django]-Testing email sending in Django
- [Django]-Django reverse lookup of foreign keys
-1👍
You can use if not
to check if a variable is False
in Django Template. *False
is made by None
, 0, []
, {}
, set()
, range(0)
and so on in Django Template same as Python and the doc explains more about if
statement in Django Template:
{% if not myvar %}
- [Django]-Where is a good place to work on accounts/profile in Django with the Django registration app?
- [Django]-How to mix queryset results?
- [Django]-Django ignores router when running tests?