You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为登录与注册页面编写成功页及失败页代码?

Alright, let's get your authentication flow sorted out. You've got the sign-in and registration pages laid out, now we need to add success/failure handling with proper redirection and error messages. Here's a step-by-step implementation:

1. Update Your Existing Sign-In/Registration Templates

First, we need to fix the forms in your existing pages to properly submit data, add error display areas, and set correct HTTP methods:

Modified signin.html

<html>
<head>
<title>Sign-In!</title>
<link rel="stylesheet" href="static/css/style2.css?q={{time}}" type="text/css">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body id="reg">
<!-- Error message display area -->
{% if error %}
<div class="alert alert-danger" role="alert">
  {{ error }}
</div>
{% endif %}

<form method="POST" action="/signin">
<label>
<p class="label-txt">ENTER YOUR EMAIL</p>
<input type="email" name="email" class="input" required>
<div class="line-box">
<div class="line"></div>
</div>
</label>
<label>
<p class="label-txt">ENTER YOUR PASSWORD</p>
<input type="password" name="password" class="input" required>
<div class="line-box">
<div class="line"></div>
</div>
</label>
<button type="submit">submit</button>
</form>
</body>
</html>

Modified register.html

<html>
<head>
<title>Register!</title>
<link rel="stylesheet" href="static/css/style2.css?q={{time}}" type="text/css">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body id="reg">
<!-- Error message display area -->
{% if error %}
<div class="alert alert-danger" role="alert">
  {{ error }}
</div>
{% endif %}

<form method="POST" action="/register">
<label>
<p class="label-txt">ENTER YOUR EMAIL</p>
<input type="email" name="email" class="input" required>
<div class="line-box">
<div class="line"></div>
</div>
</label>
<label>
<p class="label-txt">ENTER YOUR NAME</p>
<input type="text" name="name" class="input" required>
<div class="line-box">
<div class="line"></div>
</div>
</label>
<label>
<p class="label-txt">ENTER YOUR PASSWORD</p>
<input type="password" name="password" class="input" required>
<div class="line-box">
<div class="line"></div>
</div>
</label>
<button type="submit">submit</button>
</form>
</body>
</html>

Key changes here:

  • Added name attributes to inputs so Flask can access form data
  • Set method="POST" on forms (critical for submitting data securely)
  • Added Bootstrap alert component to display error messages conditionally using Jinja2 templating
  • Added required attribute for basic client-side validation
2. Create the Landing Page (index.html)

This is where users will be redirected after successful login/registration:

<html>
<head>
<title>Home</title>
<link rel="stylesheet" href="static/css/style2.css?q={{time}}" type="text/css">
</head>
<body>
<h1>Welcome to Your Dashboard!</h1>
<p>You've successfully logged in or registered.</p>
</body>
</html>
3. Update Flask Routing with Authentication Logic

We'll add validation, user storage (in-memory for demo, replace with a database in production), and proper redirection:

from flask import Flask, render_template, request, redirect, url_for
from datetime import datetime

app = Flask(__name__)

# Temporary in-memory storage (replace with SQLite/PostgreSQL in production)
registered_users = []

@app.route('/')
def index():
    return render_template('index.html', time=datetime.now())

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template('register.html', time=datetime.now())
    else:
        # Extract form data
        email = request.form.get('email')
        name = request.form.get('name')
        password = request.form.get('password')

        # Basic validation check
        if not email or not name or not password:
            return render_template('register.html', time=datetime.now(), error="Please fill in all required fields!")
        
        # Check if email is already registered
        for user in registered_users:
            if user['email'] == email:
                return render_template('register.html', time=datetime.now(), error="This email is already registered!")
        
        # Save user to storage
        registered_users.append({
            'email': email,
            'name': name,
            'password': password
        })

        # Redirect to home page on success
        return redirect(url_for('index'))

@app.route('/signin', methods=['GET', 'POST'])
def signin():
    if request.method == 'GET':
        return render_template('signin.html', time=datetime.now())
    else:
        email = request.form.get('email')
        password = request.form.get('password')

        # Validate credentials against stored users
        user = next((u for u in registered_users if u['email'] == email and u['password'] == password), None)
        
        if user:
            # Success: redirect to home page
            return redirect(url_for('index'))
        else:
            # Failure: return to sign-in page with error message
            return render_template('signin.html', time=datetime.now(), error="Invalid email or password!")

if __name__ == '__main__':
    app.run(debug=True)
4. How It Works
  • Successful Authentication: When login/registration is valid, we use redirect(url_for('index')) to send users to the home page (this prevents duplicate form submissions if the user refreshes).
  • Failed Authentication: If validation fails, we re-render the original page and pass an error variable, which is displayed in the Bootstrap alert we added earlier.
  • Temporary Storage: The in-memory list registered_users is for demo purposes—for a real app, use a proper database like SQLite, PostgreSQL, or Flask-SQLAlchemy.

内容的提问来源于stack exchange,提问作者Chelsea H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 16:17:45