【问题标题】:Django - ChoiceField cleaned_data gets String instead of IntegerDjango - ChoiceField 清理数据获取字符串而不是整数
【发布时间】:2018-05-15 22:54:22
【问题描述】:

我有一个名为“单位”的表单字段,如下所示:

    units = forms.ChoiceField(choices=[(x, x) for x in range(1, 11)], help_text = 'Units: ')

当我执行form.cleaned_data['units'] 时,我得到的是字符串而不是整数。 如何更改字段以获取整数?

【问题讨论】:

    标签: django forms integer choicefield cleaned-data


    【解决方案1】:

    我终于找到了 Field 类型 TypedChoiceField ,如果 coerced = Int 将返回 Integer。

        units = forms.TypedChoiceField(choices=[(x, x) for x in range(1, 11)], coerce=int, help_text = 'Units: ')
    

    【讨论】:

    • 谢谢!非常适合我:)
    猜你喜欢
    • 2016-06-08
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多