我使用以下代码在 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/