[Django]-Negating a boolean in Django template

30đź‘Ť

âś…

What about the yesno template tag?

{{ value|yesno:"False,True" }}
👤garnertb

23đź‘Ť

“not” should work, according to this example from the Django docs:

{% if not athlete_list %}
    There are no athletes.
{% endif %}

You can find the example here: https://docs.djangoproject.com/en/1.4/ref/templates/builtins/#boolean-operators

If you want to directly get the string representation of a boolean, i’m afraid you have to go what you describe as clunky. {{ variable }} puts out a string representation of the variables content or calls a function.


edit:

If you are really in need of getting the inverse value of a boolean, i would suggest to create a simple templatetag for that:

from django import template

register = template.Library()

@register.simple_tag
def negate(boolean):
    return (not boolean).__str__()

put that in your_app/templatetags/templatetags.py and you can use it in your template like this:

{% negate your_variable %}

quite costly, i would stick with garnertb’s answer.

👤marue

2đź‘Ť

Another way to do it is by using the add filter like this:

{{ variable_name|add:"-1" }}
  • True is 1, so, it’ll become 0 which is False

  • False is 0, so, it’ll become -1 which is True

👤Gourav Chawla

Leave a comment