Question

I seem to have problem in Django when looking for a field which has a choice parameter. I do not get the field name but instead I get the number for some odd reason.

My forms.py:

from django import forms

CONTRACT_TYPE_CHOICES = (
                 (1, 'Annual'),
                 (2, 'Ad-hoc'),
                 )

CONTRACT_STATUS_CHOICES = (
  (1, 'Active'),
  (2, 'In-Active'),
  )

class ContractForm(forms.ModelForm):
  contract_type = forms.ChoiceField(choices=CONTRACT_TYPE_CHOICES) 
  contract_status = forms.ChoiceField(choices=CONTRACT_STATUS_CHOICES) 

  class Meta:
    model = Contract

In my template. I have the following

{% for contracts in contracts_list %}
  {{contracts.client_contract_number}}<br/>
  {{contracts.contract_type}}<br/>
  {{contracts.contract_status}}<br/>
{% endfor %}

They all return a value. But contact_type and contract_status returns numbers. I do not to make it return numbers but the names. How do I do this?

Was it helpful?

Solution

Model fields that take a choices kwarg automagically get a get_FIELD_NAME_display method. So for example, you could should put this in your template:

{{ contracts.get_contract_type_display }}
{{ contracts.get_contract_status_display }}

See the documentation.

Good luck, Justin

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top