wtforms
的form.validate_on_submit()方法出现问题,每次提交表单时都会引发以下错误:
'LoginForm' object has no attribute 'validate_on_submit'
forms.py:
from wtforms import Form, validators, StringField, PasswordField
class LoginForm(Form):
email = StringField('Email Address', [validators.DataRequired(message='Field required')])
password = PasswordField('Password', [validators.DataRequired(message='Field required')])
routes.py
from flask import Flask, escape, request, render_template, redirect, url_for
from securepi import app, tools
from securepi.forms import LoginForm
@app.route('/login/', methods=['GET', 'POST'])
def login():
error = None
try:
form = LoginForm(request.form)
if request.method == "POST" and form.validate_on_submit():
email = str(form.email.data)
password = tools.encrypt(str(form.password.data))
print("email: {}, password: {}".format(email, password))
# if valid account create session and redirect to index
return redirect(url_for('index'))
else:
print("FAIL")
error = "Invalid username or password"
except Exception as e:
return(str(e))
return render_template('login.html', form = form)
和表格
<form action="" method="post">
<div class="form-group has-feedback">
<input type="email" name="email" class="form-control" placeholder="Email" value="{{ request.form.email }}">
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" name="password" class="form-control" placeholder="Password" value="{{ request.form.password }}">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<!-- /.col -->
<div class="col-xs-12">
<button type="submit" class="btn btn-primary btn-block">Log in</button>
</div>
<!-- /.col -->
</div>
</form>
答案 0 :(得分:1)
您可以尝试将Forms.py更改为以下内容吗?
from flask_wtf import FlaskForm
from wtforms import validators, StringField, PasswordField
class LoginForm(FlaskForm):
email = StringField('Email Address', [validators.DataRequired(message='Field required')])
password = PasswordField('Password', [validators.DataRequired(message='Field required')])
答案 1 :(得分:0)
Forms class文档说:
validate()
通过在每个字段上调用validate来验证表单,并将任何额外的Form.validate_
验证器传递给字段验证器。
似乎您正在尝试验证表单中缺少的on_submit
字段。只需使用validate()
就可以解决问题。