gpt4 book ai didi

python - Flask wtforms ValidationError 未向用户显示

转载 作者:行者123 更新时间:2023-12-05 06:58:51 25 4
gpt4 key购买 nike

我正在使用带输入验证的 flask wtforms。一切正常,除了验证失败,我的 ValidationError 消息没有显示给用户...

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, PasswordField, ValidationError # URLField, EmailField
from wtforms.validators import DataRequired, Email, EqualTo

class SignupForm(FlaskForm):
name = StringField("Name:", validators=[DataRequired()])
email = StringField("Email:", validators=[DataRequired(), Email()])
password = PasswordField("Password:", validators=[DataRequired(), EqualTo('pass_confirm', message='Passwords must match')])
pass_confirm = PasswordField("Confirm:", validators=[DataRequired()])
submit = SubmitField("Create Account")

def validate_email(self, field):
if User.query.filter_by(email=field.data).first():
raise ValidationError('Your email has already been registered.')

def validate_name(self, field):
if User.query.filter_by(name=field.data).first():
raise ValidationError('This username is taken.')

在我看来:

@users.route('/signup', methods=['GET','POST'])
def signup():
form = SignupForm()

if form.validate_on_submit():
url = form.name.data # todo: generate unique url
user = User(name=form.name.data,
url=url,
email = form.email.data,
password = form.password.data)
db.session.add(user)
db.session.commit()

return redirect(url_for('users.login'))

return render_template('signup.html', form=form)

这是模板:

<div class="jumbotron">
<h1>Sign up Page</h1>
<p>Please fill out the form</p>
<form method="POST">
{{ form.hidden_tag() }}
<div class="form-group">
{{ form.name.label(class='form-group') }}
{{ form.name(class='form-control') }}
</div>

<div class="form-group">
{{ form.email.label(class='form-group') }}
{{ form.email(class='form-control') }}
</div>

<div class="form-group">
{{ form.password.label(class='form-group') }}
{{ form.password(class='form-control') }}
</div>

<div class="form-group">
{{ form.pass_confirm.label(class='form-group') }}
{{ form.pass_confirm(class='form-control') }}
</div>

{{ form.submit(class='btn btn-primary') }}
</form>

</div>

提交无效表单(无效的电子邮件或姓名)后,表单只会返回空白,而不会指示用户做错了什么。如何向用户显示这些验证错误?非常感谢!

最佳答案

表单必须获取一些数据

@users.route('/signup', methods=['GET','POST'])
def signup():
form = SignupForm(request.form)

@users.route('/signup', methods=['GET','POST'])
def signup():
form = SignupForm(request.json)

关于python - Flask wtforms ValidationError 未向用户显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64528711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com