Reputation: 832
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?
Upvotes: 2
Views: 1005
Reputation: 11
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'
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.
Upvotes: 1
Reputation: 600006
You have a CharField but your choice values are ints. Use strings there instead:
DOP = '1'
PPP = '2'
Upvotes: 0