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
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 }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With