模板标签中翻译的枚举字段

发布于 2024-11-09 22:22:46 字数 689 浏览 0 评论 0原文

我尝试在模板中显示枚举的名称。要清楚的是, 我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

似梦非梦 2024-11-16 22:22:46

要显示字段值的人类可读格式,请在模型实例上使用 get_$var_display() 方法(为具有 choices 的所有字段自动创建)。对于您的示例,它是这样的:

{{ company.get_wnr_display }}

要在没有模型实例的情况下通过索引获取值,最简单的方法是编写自定义过滤器,它将存储在变量中的索引转换为所需的值:

{{ some_value|as_wnr_title }}

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 }}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文