Django:如何在给定实际值和选择的情况下访问模板中ChoiceField的显示值? [英] Django: How to access the display value of a ChoiceField in template given the actual value and the choices?

查看:127
本文介绍了Django:如何在给定实际值和选择的情况下访问模板中ChoiceField的显示值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个绑定形式的ChoiceField,其选择为:

I have a ChoiceField in a bound form, whose choices are:

[('all', 'All users'), ('group', 'Selected groups'), ('none', 'None')]

在模板中,我毫无疑问地访问其绑定值(要存储的实际值;每个元组的第一个元素)和选择。掌握了这些信息之后,我知道我应该能够访问显示值或每个元组的第二个元素。但是如何在模板中做到这一点?谢谢。

In the template, I have no problem accessing its bound value (the actual value to be stored; the first element of each tuple) and the choices. With these pieces of info in hands, I know I should be able to access the display values, or the second element of each tuple. But how can I do that in the template? Thanks.

推荐答案

我怀疑是否可以在没有自定义模板标记或过滤器的情况下完成此操作。
自定义模板过滤器可能如下所示:

I doubt that it can be done without custom template tag or filter. Custom template filter could look:

@register.filter
def selected_choice(form, field_name):
    return dict(form.fields[field_name].choices)[form.data[field_name]]

这篇关于Django:如何在给定实际值和选择的情况下访问模板中ChoiceField的显示值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆