3

I have a Choice Field in my models.py

models.py

STATUS = (
    ('closed_issue', 'Closed Issue'),
    ('open_ssue', 'Open Issue'),
    ('pending', 'Pending'),
)

class Issue(models.Model):
    name = models.CharField(max_length=45)
    status = models.CharField(max_length=50, choices=STATUS)

views.py

def Issues(resuest):
    issues = Issue.objects.all()

template

{% for issue in issues %}
     {{ issue.status }}
{% endfor %}

Output

closed_issue 
open_issue 

It displays the keys of the choice field instead of values

I want the values to be displayed in the template. Is there a way to get the values instead of keys?

Thanks for any help.

aprasanth
  • 1,079
  • 7
  • 20
  • See http://stackoverflow.com/questions/4320679/django-display-choice-value and get_FOO_display – JamesO Mar 24 '17 at 10:22

1 Answers1

7

Of course there is a way:

{{ issue.get_status_display }}

In order to get the values of the STATUSes you must use a name convention get_<field_name>_display(). More on this here.

nik_m
  • 11,825
  • 4
  • 43
  • 57
  • Also I have one more doubt What to do if I want the same thing in my view for eg ` for issue in Issues : print(issue.status)` – aprasanth Mar 24 '17 at 10:27
  • You should do the same, i.e `for issue in issues: print(issue.get_status_display())`. – nik_m Mar 31 '17 at 10:26
  • @nik_m - If I were to use a `ManyToManyField` pointing to the _key field_ of another model to get my `choice_field`, how do I display the related value of the `ManyToManyField`? – Love Putin Not War May 09 '22 at 02:46