开发者

translated enum fields in template tags

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(lab开发者_如何学JAVAel=_("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 }}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜