How can I change the way a boolean prints in a django template?

Viewed 19009

I have some django code that prints a BooleanField

it is rendered as True or False, can I change the label to be Agree/Disagree or do I need to write logic for that in the template?

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

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

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

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.

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 }}
Related