Coerce in django forms

隐身守侯 提交于 2021-02-20 06:09:43

问题


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:

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.


回答1:


TypedChoiceField is just like ChoiceField, except ChoiceField always return unicode.

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.



来源:https://stackoverflow.com/questions/18200545/coerce-in-django-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!