Home > database >  How to display a ChoiceField's text through Django template to a user?
How to display a ChoiceField's text through Django template to a user?

Time:12-14

models.py:

class Person(models.Model):
    title=models.CharField(max_length=11)
    name=models.CharField(max_length=100)
    gender=models.CharField(max_length=11)

forms.py:

class PersonForm(ModelForm):
    GENDER_SELECT = (
        ('f', 'Female'),
        ('m', 'Male'),
        ('o', 'Other'),
    )
    TITLE_SELECT = (
        ('0', 'Mr.'),
        ('1', 'Mrs.'),
        ('2', 'Ms.'),
        ('3', 'Mast.'),
    )
    title=forms.CharField(widget=forms.RadioSelect(choices=TITLE_SELECT, attrs={'class': 'form-check-inline'}))
    gender=forms.CharField(widget=forms.RadioSelect(choices=GENDER_SELECT, attrs={'class': 'form-check-inline'}))
    class Meta:
        model=Person
        fields='__all__'

Now, below are the two ways that I tried to get the data-output to the web-page through but the first one returns nothing and the second one returns the database value of the choice, rather than the text that the user selected. I want the user to see Mr. or Mrs. or Ms. or Mast. and not 0/1/2/3. What is wrong here?

template:

1

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

2

{% for rp in report %}
    <td >{{rp.title}}</td>
{% endfor %}

CodePudding user response:

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 >
    {% person_title rp.title %}
</td>
{% endfor %}

Much cleaner!

  • Related