[Answered ]-How to display a ChoiceField's text through Django template to a user?

1👍

The first solution does not work because title is a str and you are comparing it with integers. Below will work:

{% for rp in report %}
<p>
    {% if rp.title == '0' %}
        Mr.
    {% elif rp.title == '1' %}
        Mrs.
    {% elif rp.title == '2' %}
        Ms.
    {% elif rp.title == '3' %}
        Mast.
    {% endif %}
</p>
{% endfor %}

A better solution is to create a template tag.

# templatetags/report_tags.py
from django import template

register = template.Library()

titles = {
    '0': 'Mr.',
    '1': 'Mrs.',
    '2': 'Ms.',
    '3': 'Mast.',
}

@register.simple_tag
def person_title(title):
    return titles.get(title)

And inside your template:

{% load report_tags %}

{% for rp in report %}
<td class="design">
    {% person_title rp.title %}
</td>
{% endfor %}

Much cleaner!

Leave a comment