[Django]-How can I change the way a boolean prints in a django template?

109πŸ‘

βœ…

{{ bool_var|yesno:"Agree,Disagree" }}

You can also provide an additional string for the None case. See the docs for yesno for details.

πŸ‘€Ayman Hourieh

3πŸ‘

Any of the following may be tried with consistent results:

A.

{% if  form.my_bool.value %} 
    {{ "Yes" }} 
{% else %} 
    {{ "No" }} 
{% endif %} 

B.

{{ form.my_bool.value|yesno }}

C.

{{ form.my_bool.value|yesno:"Yes,No" }}

D.

{% if form.my_bool.value == True %} Yes {% else %} No {% endif %}

Or simply,

{{ form.my_bool.value }}    # Here the output will be True or False, as the case may be.

2πŸ‘

Just another way if you want to have more options like adding HTML elements and classes

{% if var == True %} Yes {% else %} No {% endif %}

You can change Yes and No to any html element; an image or span element

πŸ‘€Majali

1πŸ‘

If your models have been defined as

class mymodel(models.Model):
    choices=((True, 'Agree'), (False,'Disagree'),(None,"Maybe"))
    attr = models.BooleanField(choices=choices, blank=False, null=True)

You can use the built-in method to retrieve the "pretty" string associated with the value by in your template with

{{ object.get_attr_display }}

Leave a comment