Django形式的强制 [英] Coerce in django forms
问题描述
在Django形式中,强制性参数有什么作用?我已经阅读了该文档,但是它不是很有帮助,因此,对一些用例示例进行很好的解释将很有帮助.引用文档:
What does the coerce argument do in django forms? I've read the documentation, but its not very helpful, so a good explanation with a few examples of use cases would be helpful. To quote the documentation:
一个带有一个参数并返回强制值的函数.示例包括内置的int,float,bool和其他类型.默认为身份功能.
A function that takes one argument and returns a coerced value. Examples include the built-in int, float, bool and other types. Defaults to an identity function.
推荐答案
TypedChoiceField类似于ChoiceField,只是ChoiceField始终返回Unicode.
TypedChoiceField is just like ChoiceField, except ChoiceField always return unicode.
使用TypedChoiceField传递一个函数,该函数接受一个参数,并将值强制转换为所需的类型.例如,如果要将值强制转换为整数,请使用:
With TypedChoiceField you pass a function that takes one argument and returns the value cast to the type you want. For example, if you want to coerce the value to integer, use:
int_field = forms.TypedChoiceField(choices=SOME_CHOICES, coerce=int)
该字段值将始终为整数或验证失败.
The field value will always be an integer or fail validation.
这篇关于Django形式的强制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!