flask表单验证错误提示问题

问题描述

写了一个修改密码的表单,在验证表单时,在后台写的错误信息无法显示到前端留出的错误信息<span>,前端始终出现默认的Fillout this field
图片描述

部分后端是这样写的:

在forms.py:

class PwdForm(FlaskForm):
    old_pwd = PasswordField(
        label="旧密码",
        validators=[
            DataRequired("请输入旧密码")
        ],
        description="旧密码",
        render_kw={
            "class": "form-control",
            "placeholder": "请输入旧密码"
        }
    )
    submit = SubmitField(
        "确认",
        render_kw={
            "class": "btn btn-primary"
        }
    )

在views.py:

@admin.route("/pwd_reset/", methods=["GET", "POST"])
@admin_login_req
def pwd_reset():
    form = PwdForm()
    if form.validate_on_submit():
        data = form.data
        admin = Admin.query.filter_by(name=session["admin"]).first()
        from werkzeug.security import generate_password_hash
        admin.pwd = generate_password_hash(data["new_pwd"])
        db.session.add(admin)
        db.session.commit()
        flash("修改密码成功,请重新登录", "ok")
        redirect(url_for("admin.logout"))
    return render_template("admin/pwd_reset.html", form=form)

前端HTML里这样:

<label for="input_pwd">{{ form.old_pwd.label }}</label>
{{ form.old_pwd }}
{% for err in form.old_pwd.errors %}
<span style="color: #ff4f1f">{{ err }}</span>
{% endfor %}

可是这个当我提交时未输入旧密码时只是一个默认的提示信息,提交新的密码也没有成功跳转,是哪里出了问题,谢谢

阅读 5.1k
1 个回答

我的项目里是这样写的,

form.py

class ChangePasswordForm(FlaskForm):
    old_password = PasswordField('旧密码', validators=[DataRequired()])
    password = PasswordField('密码', validators=[DataRequired(), EqualTo('password2', message='密码必须一致!')])
    password2 = PasswordField('重输密码', validators=[DataRequired()])
    submit = SubmitField('更新密码')

view.py

@admin.route('/password', methods=['GET', 'POST'])
@login_required
@admin_required
def password():
    change_password_form = ChangePasswordForm(prefix='change_password')
    if change_password_form.validate_on_submit():
        if current_user.verify_password(change_password_form.old_password.data.strip()):
            current_user.password = change_password_form.password.data.strip()
            # db.session.add(current_user)
            db.session.commit()
            flash({'success': '您的账户密码已修改成功!'})
        else:
            flash({'error': '无效的旧密码!'})

    return render_template('admin/password.html', changePasswordForm=change_password_form)

html 页面

{% extends 'admin/common/base.html' %}
{% block content %}
<div class="admin-content">
    <div class="row">
        <div class="col-xs-12 col-sm-offset-2">
            <form method="post" role="form">
                {{ changePasswordForm.hidden_tag() }}
                <div class="col-xs-12 col-sm-8">
                    {% include 'admin/common/alert.html' %}<!-- flash提示 end -->
                    <!-- 错误信息changePasswordForm提示 -->
                    {% for field_name, field_errors in changePasswordForm.errors|dictsort if field_errors %}
                        {% for error in field_errors %}
                            <div class="error">
                                <div class="alert alert-danger alert-dismissible" role="alert" style="margin: 20px">
                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                    <strong>{{ changePasswordForm[field_name].label }}错误:</strong> {{ error }}
                                </div>
                            </div>
                        {% endfor %}
                    {% endfor %}
                    <!-- 错误信息changePasswordForm提示 end -->
                    <div class="input-group">
                        <span class="input-group-addon" id="basic-addon1"><i class="glyphicon glyphicon-lock"></i> </span>
                        {{ changePasswordForm.old_password(class="form-control", placeholder="输入旧密码", required="", autofocus="") }}
                    </div>
                    <div class="input-group">
                        <span class="input-group-addon" id="basic-addon2"><i class="glyphicon glyphicon-lock"></i> </span>
                        {{ changePasswordForm.password(class="form-control", placeholder="输入新密码", required="") }}
                    </div>
                    <div class="input-group">
                        <span class="input-group-addon" id="basic-addon3"><i class="glyphicon glyphicon-lock"></i> </span>
                        {{ changePasswordForm.password2(class="form-control", placeholder="再次输入新密码", required="") }}
                    </div>
                    <div class="pull-right">
                        <input class="btn btn-default" type="reset" value="重 置">
                        {{ changePasswordForm.submit(class="btn btn-primary") }}
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

详尽的内容你可以看我的项目:
https://github.com/eastossifr...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题