Fabrice Jaouën
Fabrice Jaouën

Reputation: 199

With Django, how to display User friendly names in the template using grouper?

My model offers a choice list:

class Interview(models.Model):
    class InterviewStatus(models.Model):
        PENDING = '1-PDG' 
        XED = '0-XED'
        DONE = '2-DON'
        COMPLETE = '3-COM'
        ITW_STATUS = [
            (PENDING, "Interview Planned"),
            (XED, "Interview Cancelled"),
            (DONE, "Interview Done"),
            (COMPLETE, "Interview Done and Assessed")
        ]

which is implemented in the model fields:

status = models.CharField(max_length=5,
                            blank=False,
                            null=False,
                            default=InterviewStatus.PENDING,
                            choices=InterviewStatus.ITW_STATUS,
                            verbose_name="Statut de l'interview")

When creating a new object, everything is OK. My template is written as such :

{% regroup object_list by status as status_list %}
    <h1 id="topic-list">Interview List</h1>
    <ul>
        {% for status in status_list %}
        <li><h2>{{ status.grouper }}</h2></li>
            <ul>
                {% for interview in status.list %}
                    <li><a href="{{ interview.get_absolute_url }}">{{ interview.official }}{{ interview.date_effective }} </a></li>
        {% endfor %}
            </ul>

What I get as an outcome in my browser is:

. 1-PDG

etc.

My Question is: How could I obtain the User friendly names instead of the values, which are supposed to be displayed exclusively in the html field:

<option value="1-PDG" selected>Interview Planned</option>

Upvotes: 1

Views: 346

Answers (2)

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21802

The group.list is just a python list and in templates you can index by using variable.<index> so you can get the first object in the list and use it's get_FOO_display method [Django docs] to display the human friendly name:

{% regroup object_list by status as status_list %}
    <h1 id="topic-list">Interview List</h1>
    <ul>
        {% for status in status_list %}
            <!-- Use `status.list.0.get_status_display` here -->
            <li><h2>{{ status.list.0.get_status_display }}</h2></li>
            <ul>
                {% for interview in status.list %}
                    <li><a href="{{ interview.get_absolute_url }}">{{ interview.official }}{{ interview.date_effective }} </a></li>
                {% endfor %}
            </ul>

Upvotes: 1

Ranjan MP
Ranjan MP

Reputation: 381

To display the user friendly names you have given instead of the values.

<option value="1-PDG" selected>{{ interview.get_status_display }}</option>

{{ instance.get_field_display }}

In your case instance is interview, field is status

Upvotes: 1

Related Questions