我在Flask-wtforms中使用以下代码。我在SelectField中尝试使用和不使用各种验证器,但是在用户第一次提交表单时,验证返回false。
我还尝试删除额外的验证方法,但仍然在SelectField中留下验证器,并且在第一次提交时再次验证返回False。
基本上我想知道SelectField是否未设置为-1(即已由view方法填充,并且可能用户对当前活动项目感到满意)。我不知道为什么表格如果在第二次提交时有效,即使表格中没有选择任何其他内容
forms.py
something = SelectField(label = 'Something', choices = [('-1','Select Something')], default=('-1','Select Something'), id='select_something', validators=[validators.DataRequired(message='Nothing selected')])
#NB the line below with no validator also prints "--validate() returned false"
#something = SelectField(label = 'Something', choices = [('-1','Select Something')], default=('-1','Select Something'), id='select_something')
submit = SubmitField('Submit')
def validate(self):
rv = Form.validate(self)
if not rv:
print("--validate() returned false")
return False
#the line below never fired, see fix in following line
#if self.something.data == -1:
if str(self.something.data) == '-1':
logger.debug("--validate() data==-1")
return False
return True
view.py
form = Something(request.form)
if request.method == 'GET':
#get tuple_list from database
...
form.something.choices = tuple_list
form.something.default = tuple_list[0]
if request.method == 'POST' and form.validate():
print('Something added.')
答案 0 :(得分:1)
我在每个选择元组的第一部分使用字符串而不是整数(即应该是(1,'text'))而不是正确设置默认值(只需设置default = n,其中n =整数)。
请注意此处的form.process()调用:How do you set a default value for a WTForms SelectField?
以下修复:
views.py
form = Something(request.form)
#get tuple_list from database
...
form.something.choices = tuple_list
form.something.default = tuple_list[0][0] #integer id value
form.process()
if request.method == 'POST' and form.validate():
return self.render_template('it_works.html')
return self.render_template('select_something.html')
forms.py
#no validator used here
something = SelectField(label = 'Something', choices = [], id='select_something')
submit = SubmitField('Submit')
def validate(self):
if len(self.something.choices) == 0:
return False
return True