【发布时间】:2020-02-14 05:50:08
【问题描述】:
我正在以相同的方法验证三个表单,我能够验证三个表单中的两个,但第三个表单没有验证。
views.py
......
@main.route('/tournament/<tid>', methods=["GET", "POST"])
def tournament(tid):
......
form1 = AddTeamForm()
form2 = CreateTeamForm()
form3 = CreateMatchForm()
# Dynamic allocation of team choices
team_choices = [(team.id, team.name) for team in tournament.teams]
form3.team1.choices = team_choices
form3.team2.choices = team_choices
if form1.validate_on_submit():
.....
return redirect(url_for('main.tournament', tid=tid))
if form2.validate_on_submit():
.....
return redirect(url_for('main.tournament', tid=tid))
if form3.validate_on_submit():
print('Passed the validation')
team1 = Team.query.get(int(form3.team1.data))
team2 = Team.query.get(int(form3.team2.data))
match = Match(
tournment_id=tid,
name=team1.name+' Vs '+team2.name,
match_date=form3.match_date.data)
match.teams.append(team1)
match.teams.append(team2)
db.session.add(match)
db.session.commit()
return redirect(url_for('main.tournament', tid=tid))
return render_template(
'main/tournment.html',
form1=form1,
form2=form2,
form3=form3)
forms.py
....
class CreateMatchForm(FlaskForm):
team1 = SelectField('Team1', coerce=int, validators=[DataRequired()])
team2 = SelectField('Team2', coerce=int, validators=[DataRequired()])
match_date = DateField('Match Date', validators=[DataRequired()],
render_kw={'type': 'date'},
default=date.today()+timedelta(days=1))
submit = SubmitField('Create New Match')
tournment.html
....
<form class="form-inline" method="POST" action="{{ url_for('main.tournament', tid=tid) }}">
{{ form3.hidden_tag() }}
{{ form3.team1(class="form-control m-2")}}
{{ form3.team1(class="form-control m-2")}}
{{ form3.match_date(class="form-control m-2")}}
{{ form3.submit(class="form-control m-2 btn btn-success btn-sm")}}
</form>
这是 UI 的外观:
发布请求后:
它甚至没有打印打印/错误消息。
第三种形式没有验证任何值,所以没有创建匹配。我尝试在烧瓶外壳中使用相同的脚本创建匹配项,它完美地工作并且正在创建匹配项,但我无法使用此表单创建。我该如何度过呢?
【问题讨论】:
-
form2验证成功了吗? -
@janmpeterka 是的,蓝色药丸中的名称是使用 form2 创建的。
-
它们已创建,但是否经过验证?尝试在您的代码中找出事情停止按预期发生的确切位置。
-
@janmpeterka 是的,它们是被创建的。提交 form3 后,我将使用之前填写的表单值重定向回同一页面,并且不会在命令提示符上打印任何错误消息。为了检查 form3 是否得到验证,我将打印语句作为第一行,它甚至没有打印。所以,可能是 form3 没有验证,我没有发现任何不验证该表单的问题。
-
如果你的
print没有被执行,我猜这个代码分支根本没有运行。如果 form1 或 form2 验证成功,它会运行重定向,之后不会执行任何代码(包括 form3 验证)。
标签: python forms flask flask-wtforms wtforms