Flask登录系统提交表单后用户不存在或密码错误如何弹出提示弹窗?
需求实现步骤
1. 修正登录页表单提交逻辑
你当前的login.html里提交按钮外层套了跳首页的a标签,会导致表单提交被拦截,先修改这部分,同时把密码输入框类型改为password避免明文显示:
<form action="/login" method="POST"> <input type="text" name="email" placeholder="email:" required> <br> <input type="password" name="password" placeholder="password:" required> <br> <!-- 移除外层跳首页的a标签,保证表单正常提交 --> <input type="submit" value="Submit"> </form>
2. 调整后端登录路由逻辑
Flask的flash功能依赖session,所以必须先给app配置SECRET_KEY,登录验证失败时存入flash消息再重定向到首页:
# 导入必需模块,如果你还没导入的话加上这行 from flask import flash, redirect, url_for # 配置SECRET_KEY,生产环境请替换为复杂随机字符串 app.secret_key = 'your_secret_key_keep_it_safe' @app.route("/login", methods = ['GET', 'POST']) def login(): if request.method=='GET': return render_template("login.html") else: email = request.form['email'] password = request.form['password'] user = get_user(email) if user is not None: if user.password == password: return render_template("home.html") else: # 密码错误存入提示消息 flash('请先注册') return redirect(url_for('index')) else: # 账号不存在存入提示消息 flash('请先注册') return redirect(url_for('index'))
3. 首页添加弹窗渲染逻辑
在首页index.html的</body>标签前添加flash消息读取和弹窗逻辑,打开首页时如果检测到有提示消息就弹出:
{% with messages = get_flashed_messages() %} {% if messages %} {% for msg in messages %} <script> alert("{{ msg }}"); // 若需要点击确定后刷新首页可取消注释下一行 // window.location.reload(); </script> {% endfor %} {% endif %} {% endwith %}
可选优化:登录页直接弹窗后跳转
如果你不想先跳首页再弹窗,希望在登录页直接弹出提示,用户点确定后再跳首页,可以不用flash,直接给登录模板传错误参数:
- 后端登录失败部分改为:
# 密码错误分支 else: return render_template('login.html', error_msg='请先注册') # 账号不存在分支 else: return render_template('login.html', error_msg='请先注册')
- login.html的
</body>前添加:
{% if error_msg %} <script> alert("{{ error_msg }}"); window.location.href = "{{ url_for('index') }}"; </script> {% endif %}
内容的提问来源于stack exchange,提问作者AH365
相关产品推荐
相关产品推荐

