flask-wtf selectField选项无效 [英] flask-wtf selectField choices not valid
问题描述
我这样创建了一个SelectField:
I made a SelectField like this:
# constants.py
QUESTION_LIST = {}
QUESTION_LIST['QuestionOne'] = { 'disagree-strong': "Strongly Disagree", 'agree-strong': "Strongly Agree" }
#forms.py
from constants import *
typeone = SelectField('QuestionOne',
choices=QUESTION_LIST['QuestionOne'].iteritems(),
description='Answer the question')
因此,当您加载页面时,它会显示选择.我选择了该选项,然后按Submit并说这不是有效的选择",它使选择字段空白.
So when you load the page, it shows the choices. I pick the choice, press submit and it says "this is not a valid choice" and it blanks out the select field.
然后,刷新页面时,就好像代码已损坏并且不再显示任何选择...这是一个空的下拉列表/选择字段.
Then when you refresh the page, it's as if the code is broken and it doesn't show choices anymore... It's an empty dropdown/select field.
我在做什么错了?
由于某种原因,当您将迭代项而不是表单置于视图中时,一切正常. Flask-WTF有点古怪,如果您不使用它们的格式,则似乎在提交表单后会删除选择.
For some reason, when you put the iteritems in the view instead of the form ,everything works. Some sort of quirk with Flask-WTF where if you don't use their format it seems to delete the choices after you submit form.
推荐答案
也许问题在于您在dict中的键是一个字符串.我以前遇到过这个问题,所以也许这样会有所帮助:
Maybe the problem is that your keys in dict are a strings. I had this issue before, so maybe something like this would help:
typeone = SelectField("Question1", coerce=str, choices=QUESTION_LIST['QuestionOne'])
这个coerce
东西帮助了.我认为所有POST数据都是unicode,并且默认情况下coerce
也等于unicode(至少在WTF格式中,如果确实使用Unicode,则需要检查Flask-WTF扩展名).您的选择键是字符串.
This coerce
thingie helped. What happens I think that all POST data is unicode and by default coerce
is also equals to unicode (at least in WTF forms, need to check Flask-WTF extension if you do use one). And your choices keys are strings.
这篇关于flask-wtf selectField选项无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!