Django template – get object's choice field text

Question:

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?

Asked By: Ljubisa Livac

||

Answers:

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

DOP = '1'
PPP = '2'
Answered By: Daniel Roseman

Create a model like this:

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

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

And then you can access keys:

{{ person.contract_choices }}

returns: ‘DOP’ or ‘PPP’

Or if you want values:

{{ person.get_contract_choices_dysplay }}

returns: ‘always’ or ‘sometimes’

EDIT: Proper way according to Django’s documentation

Integer type in DB might be better in you case. You can create subclass of Django’s models.IntegerChoices

class Person(models.Model):

    class ContractType(models.IntegerChoices):
        DOP = 0, 'always'
        PPP = 1, 'sometimes'

    contract = models.IntegerField(
        "Contract", choices=ContractType.choices, default=0
    )

and get it in template as {{ person.get_contract_display }}

Please refer to choices in Django docs for more details.

Answered By: user2944551