我无法在Flask中获取错误消息进行渲染。 我怀疑这与蓝图有关。以前,在views.py中看到的逻辑在用户蓝图中,但我已将其移植到主蓝图上。无论如何,从那时起,我无法获得要呈现的错误消息。
我认为我遇到问题的具体方法是:
self.email.errors.append(“此电子邮件已注册”)
@main_blueprint.route('/', methods=['GET', 'POST'])
@main_blueprint.route('/<referrer>', methods=['GET', 'POST'])
def home(referrer=None):
form = RegisterForm(request.form)
# prepares response
resp = make_response(render_template('main/index.html', form=form))
if form.validate_on_submit():
do_stuff()
return resp
<h1>Please Register</h1>
<br>
<form class="" role="form" method="post" action="">
{{ form.csrf_token }}
{{ form.email(placeholder="email") }}
<span class="error">
{% if form.email.errors %}
{% for error in form.email.errors %}
{{ error }}
{% endfor %}
{% endif %}
</span>
</p>
<button class="btn btn-success" type="submit">Register!</button>
<br><br>
<p>Already have an account? <a href="/login">Sign in</a>.</p>
</form>
class RegisterForm(Form):
email = TextField(
'email',
validators=[DataRequired(), Email(message=None), Length(min=6, max=40)])
def validate(self):
print "validating"
initial_validation = super(RegisterForm, self).validate()
if not initial_validation:
print "not initial validation"
return False
user = User.query.filter_by(email=self.email.data).first()
print user
if user:
print self
print "error, email already registered"
self.email.errors.append("This Email is already registered")
return False
return True
尝试调试时,“print user”的值为:
project.user.forms.RegisterForm对象位于0x7fa436807698
答案 0 :(得分:0)
让它工作,@ glls,你是对的。把代码写成:
@main_blueprint.route('/', methods=['GET', 'POST'])
@main_blueprint.route('/<referrer>', methods=['GET', 'POST'])
def home(referrer=None):
# prepares response
resp = make_response(render_template('main/index.html', form=form))
if form.validate_on_submit():
do_stuff()
form = RegisterForm(request.form)
return resp