我的表单设置如下,最终,在调试模式下出现的错误是sqlalchemy.exc.IntegrityError:(sqlite3.IntegrityError)UNIQUE约束失败。我知道为什么,但是我希望将此错误提示给用户,以便他们知道问题所在。
class RegistrationForm(FlaskForm):
company_url = StringField('Company Website', validators=[DataRequired(), URL(message='Must be a valid URL')])
password = PasswordField(
'Password', validators=[DataRequired(), EqualTo('pass_confirm',
message='Passwords must match')]
)
pass_confirm = PasswordField('Confirm Password', validators=[DataRequired()])
submit = SubmitField('Register!')
但是,当不正确的URL结构输入到表单中并提交后,我无法使它在用户的html页面中刷新错误消息。html页面如下。我也将base.html放在下面。
{% extends "base.html" %}
{% block content %}
<form method="POST">
{{form.hidden_tag()}}
{{form.company_url.label}}{{form.company_url()}}<br>
{{form.password.label}}{{form.password()}}<br>
{{form.pass_confirm.label}}{{form.pass_confirm()}}<br>
{{form.submit()}}
</form>
{% endblock %}
<!DOCTYPE html>
<html>
<head>
...some code here
</head>
<body>
<!-- Just an image -->
<nav class="navbar navbar-dark bg-dark">
<span class="align-bottom text-light">Creating connections, saving time</span>
</nav>
{% with messages = get_flashed_messages() %} {% if messages %} {% for
message in messages %}
<div class="alert alert-warning alert-dismissible" role="alert">
<button
type="button"
class="close"
data-dismiss="alert"
aria-label="Close"
>
<span aria-hidden="true">×</span>
</button>
{{message}}
</div>
{% endfor %} {% endif %} {% endwith %} {% block content %} {% endblock %}
</body>
</html>
views.py是:
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
user = Buyers(
company_url=form.company_url.data,
password=form.password.data
)
db.session.add(user)
db.session.commit()
flash("Thank you for registering.")
return redirect(url_for('login'))
return render_template('register.html', form=form)
如何处理表格错误,以确保用户知道他们输入的URL结构不正确?我处于调试模式,现在,register.html页面基本上只是重新加载,没有任何关于原因的消息。谢谢!
问题来源:stackoverflow
views.py:
import validators
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
isUrlValid=validators.url(form.company_url.data)
if isUrlValid==True:
user = Buyers(
company_url=form.company_url.data,
password=form.password.data
)
db.session.add(user)
db.session.commit()
flash("Thank you for registering.")
return redirect(url_for('login'))
else:
flash("URL is not valid. Please enter a valid URL")
return redirect(url_for('register'))
return render_template('register.html', form=form)
回答来源:stackoverflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。