1

lets say I have a dictionary called credit_facilities, where I map credit facility id to its verbal reprsentation.

credit_facilities = {1 : 'Yes',2:'No',3:'Not sure'}

I have model object where I retrieve values to be used as key for the dictionary. For instance lets say the model is named "customer" and it has attribute called "credit_facility". So, customer.credit_facility give either 1,2 or 3. I want to use this value as a key in dictionary. Meaning, is there an equivalent in django template language for the follwoing epression.

credit_facilities[customer.credit_facility]
MrSir
  • 33
  • 3
  • Write a custom template filter : See that post : http://stackoverflow.com/questions/8000022/django-template-how-to-look-up-a-dictionary-value-with-a-variable – Wilfried Dec 30 '16 at 12:09
  • 2
    You should set this as the choices attribute for your field, then you would be able to do `customer.get_credit_facility_display` in the template. – Daniel Roseman Dec 30 '16 at 12:12

1 Answers1

2

Use a choices argument for your credit_facility field and the (automagic) get_credit_facility_display() method to get the associated label:

class Customer(models.Model):
    CREDIT_FACILITY_CHOICES = (
      (1, "Yes"),
      (2, "No"),
      (3, "Not sure")
      )
    credit_facility = models.IntegerField(
       "credit facility", 
       choices = CREDIT_FACILITY_CHOICES
       )

then:

>>> c = Customer(1)
>>> c.get_credit_facility_display()
"Yes"

Full documentation here : https://docs.djangoproject.com/en/1.10/ref/models/fields/#choices

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118