Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negating a boolean in Django template

Is there a way to negate a python boolean variable in a template using Django? I've tried both of the following:

<td>{{ !variable_name }}</td>
<td>{{ not variable_name }}</td>

But both gave me a TemplateSyntaxError.

I realize that I could do:

<td>{% if variable_name %} False {% else %} True {% endif %}</td>

But this seems really clunky. I was hoping there might be a cleaner method.

like image 597
StephenTG Avatar asked Feb 21 '14 18:02

StephenTG


People also ask

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

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.

What is block in Django template?

Definition and Usage In master templates the block tag is a placeholder that will be replaced by a block in a child template with the same name. In child templates the block tag is content that will replace the placeholder in the master template with the same name.

What does the built in Django template tag Lorem do?

lorem tag displays random “lorem ipsum” Latin text. This is useful for providing sample data in templates.


3 Answers

What about the yesno template tag?

{{ value|yesno:"False,True" }}
like image 99
garnertb Avatar answered Oct 02 '22 00:10

garnertb


"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.

like image 23
marue Avatar answered Oct 02 '22 00:10

marue


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

like image 1
Gourav Chawla Avatar answered Oct 02 '22 01:10

Gourav Chawla