菜鸟问题。我正在建立一个登录/注册页面,在注册页面上,我使用flask_wtf来验证某些内容,例如密码长度,电子邮件格式以及用户提供的两个密码是否匹配。这是我正在使用的flask_wtf代码。
# import statements omitted for brevity
class RegistrationForm(FlaskForm):
username = StringField('Username',
validators=[DataRequired(), Length(min=2, max=20)])
email = StringField('Email',validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
confirm_password = PasswordField('Confirm Password',
validators=[DataRequired(),Length(min=4, max=20), EqualTo('password')])
submit = SubmitField('Sign Up')
检查输入后,我正在使用sqlalchemy来检查数据库中是否已经存在用户名和电子邮件。我现在面临的问题是我无法获取flask_wtf来验证表格。我可以键入任何想要的内容,它将转换为sql查询。这是我处理注册和用户输入验证的两条烧瓶路线。
@app.route('/register',methods=['GET','POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
return redirect(url_for('check_user_input'))
return render_template('register.html',form=form)
@app.route('/status',methods=['POST'])
def check_user_input():
name = request.form.get("username")
email = request.form.get("email")
password = request.form.get("password")
if db.execute("SELECT * FROM DB WHERE username= :username",{"username":name}).rowcount==1:
return render_template("404.html", message="Sorry username already exists")
elif db.execute("SELECT * FROM DB WHERE email= :email",
{"email":email}).rowcount==1:
return render_template("404.html", message="Sorry email already exists")
else:
db.execute("INSERT INTO DB (username,email,password) VALUES
(:username,:email,:password)",
{"username":name, "email":email,"password":password})
db.commit()
return render_template("success.html")
如何获取flask_wtf表单首先进行验证,然后将输入交给check_user_input()
函数?
我的register.html包含以下行。
<form class="form-signin" method="POST" action="{{url_for('check_user_input')}}">
任何帮助将不胜感激。
答案 0 :(得分:0)
一种方法是向表单添加自定义验证:
class RegistrationForm(FlaskForm):
username = StringField('Username',
validators=[DataRequired(), Length(min=2, max=20)])
email = StringField('Email',validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
confirm_password = PasswordField('Confirm Password',
validators=[DataRequired(),Length(min=4, max=20), EqualTo('password')])
submit = SubmitField('Sign Up')
def validate(self):
rv = FlaskForm.validate(self)
if not rv:
return False
if db.execute("SELECT * FROM DB WHERE username= :username",{"username":self.username.data}).rowcount>0:
self.username.errors.append('Sorry username already exists')
return False
if db.execute("SELECT * FROM DB WHERE email= :email", {"email":self.email.data}).rowcount>0:
self.email.errors.append('Sorry email already exists')
return False
return True