python - SelectField 返回值 wtf-forms

标签 python forms

我使用以下代码在 python 中创建了一个 SelectField:

condition = SelectField(u'Condition', choices = [(1,condition_string[5]),(2, condition_string[4]),(3, condition_string[3]),(4, condition_string[2]),(5, condition_string[1])], validators =[validators.Required(message=u'Must enter the condition of the book')])

我的问题是:当用户提交他们的选择时,html 会返回什么: 它会返回 condition_string[] 中的值还是返回列表中排序的数字, 例如:如果use选择第一个选项,它会返回'1'还是condition_string[5]中的值?

最佳答案

都不是。

来自WTForms docs :

Select fields keep a choices property which is a sequence of (value, label) pairs. The value portion can be any type in theory, but as form data is sent by the browser as strings, you will need to provide a function which can coerce the string representation back to a comparable object.

(格式错误的)问题是,

"what will be returned from the html?"

我假设你想问这样的问题:

what will the value of condition.data be after processing data received from a browser?

答案是:一个字符串。它可能是字面上的任何字符串——这就是为什么你必须验证。

但如果用户合作,浏览器将以字符串形式发回,并且 condition.data 将返回 u'1 'u'2' 等。请注意,(值,标签) 对中的第一个元素并且不一定是它在 choices 列表中的位置。

事实上,该字段永远不会验证,因为作为值 (int) 提供的数字将与字符串数据(默认情况下强制转换为 unicode)不匹配。这就是为什么文档说,"you will need to provide a function which can coerce the string representation back to a comparable object."

关于python - SelectField 返回值 wtf-forms,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27933039/

相关文章:

JavaScript:如何使 div 的样式依赖于在选择框中选择的选项?

python - 检查给定列表中的元素是否存在于 DataFrame 的数组列中

python - 通过组合字符串python变量调用

python - 对数据框中的列中的数据进行分类

php - 搜索结果和后退按钮/HTML 表单

PHP删除表单用于从MySQL数据库中删除数据

javascript - 提交表单而不打开新窗口或选项卡

php - 如何从 PHP 发送固定值到数据库

Python 一行打印当前目录中的每个文件

python - "ImportError no module named gnuradio"尝试执行 ./uhd_fft