translated enum fields in template tags
Asked Answered
U

1

8

I try to show the name of an enum in the template.To be clear, I have enum like class in model.py

class EmployerWorkerNumberRange():
R_0 = 0
R_1_5 = 1
R_6_15 = 2
UNKNOWN = 3

EMPLOYER_WORKER_NUMBER_RANGE =(
    (R_0,_("wnr_0")),
    (R_1_5 ,_("wnr_1_5")),
    (R_6_15,_("wnr_6_15")),
    (UNKNOWN,_("UnknownWorkerNumberRange")),
)

When I use it in form like

wnr = forms.ChoiceField(label=_("emp_full_reg_wnr"), required=True, choices=EmployerWorkerNumberRange.EMPLOYER_WORKER_NUMBER_RANGE)

it works great.(Fills the dropdown with translated values and when I get the selected item it turns just the id)

My question is how can I show any translated value in my template by giving the id of it. For example, I would like to use it EmployerWorkerNumberRange.EMPLOYER_WORKER_NUMBER_RANGE[0]

Could you suggest me any way ?

Thanks

Uppercut answered 25/5, 2011 at 12:6 Comment(0)
S
17

To show human-readable from of field value, use get_$var_display() method (created automatically for all fields with choices) on model instance. For your example it's something like this:

{{ company.get_wnr_display }}

To get value by index without model instance, the easiest way is write custom filter that will convert index stored in a variable to needed value:

{{ some_value|as_wnr_title }}
Spathic answered 25/5, 2011 at 16:5 Comment(2)
It works perfect,thanks! Is there any document that I can read about such things? I have read the django documentations but I haven't noticed such usage..Uppercut
It's all in django documentation, you might've been looking at wrong sections. This particular method is here: docs.djangoproject.com/en/1.3/ref/models/instancesSpathic

© 2022 - 2024 — McMap. All rights reserved.