Django形式的强制 [英] Coerce in django forms

查看:51
本文介绍了Django形式的强制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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屋!

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