模板标签中翻译的枚举字段
我尝试在模板中显示枚举的名称。要清楚的是, 我在 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")),
)
等形式使用它时
当我以wnr = forms.ChoiceField(label=_("emp_full_reg_wnr"), required=True, Choices=EmployerWorkerNumberRange.EMPLOYER_WORKER_NUMBER_RANGE )
它工作得很好。(用翻译后的值填充下拉列表,当我获得所选项目时,它只是id)
我的问题是如何通过给出模板的 id 来显示模板中的任何翻译值。 例如,我想使用它 EmployerWorkerNumberRange.EMPLOYER_WORKER_NUMBER_RANGE[0]
您能给我建议吗?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要显示字段值的人类可读格式,请在模型实例上使用
get_$var_display()
方法(为具有choices
的所有字段自动创建)。对于您的示例,它是这样的:要在没有模型实例的情况下通过索引获取值,最简单的方法是编写自定义过滤器,它将存储在变量中的索引转换为所需的值:
To show human-readable from of field value, use
get_$var_display()
method (created automatically for all fields withchoices
) on model instance. For your example it's something like this: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: