pythondjangotemplatesdjango-modelschoicefield

Django template - get object's choice field text


This is my model:

class Person(models.Model):
    ...
    DOP = 1
    PPP = 2
    contract_choices = (
        (DOP, 'always'),
        (PPP, 'sometimes'),
    )

    contract = models.CharField(max_length=3, choices = contract_choices)
    ...

I need contract field value in my template:

{% for person in persons %}
{{ person.get_contract_display }}
{% endfor %}

gives me '1' (or '2') instead of 'always' (or 'sometimes'). How can i get that string text instead of integer value?


Solution

  • You have a CharField but your choice values are ints. Use strings there instead:

    DOP = '1'
    PPP = '2'