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

表单提交后刷新页面重复发送POST请求致数据库重复数据的问题求助

表单提交后刷新页面重复发送POST请求致数据库重复数据的问题求助

我遇到了一个头疼的问题:在网站提交表单时,输入的数据会正常保存到数据库,但如果刷新页面或者重新打开网站,系统会自动发送一次POST请求,把相同的数据再次存入数据库,造成重复记录。

我的代码如下:

Python 代码

from datetime import datetime
from flask import Flask, render_template, request, flash, redirect, url_for
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)
app.config["SECRET_KEY"] = "xDxDxD"
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///data.db"
db = SQLAlchemy(app)


class Form(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(80))
    last_name = db.Column(db.String(80))
    email_add = db.Column(db.String(150))
    date = db.Column(db.Date)
    occupation = db.Column(db.String(80))


@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        first_name = request.form["first_name"]
        last_name = request.form["last_name"]
        email_add = request.form["email"]
        date = request.form["date"]
        date_obj = datetime.strptime(date, "%Y-%m-%d")
        occupation = request.form["occupation"]

        form = Form(first_name=first_name, last_name=last_name, email_add=email_add, date=date_obj, occupation=occupation)
        db.session.add(form)
        db.session.commit()
        flash(f"{first_name}, your form was submitted successfully", "success")

    return render_template("index.html")


if __name__ == "__main__":
    with app.app_context():
        db.create_all()
        app.run(debug=True, port=5001)

HTML 代码

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title>Job Form</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    </head>
    <body>
        <div class="container">
            <h1 class="mt-4 mb-4">Job Application Form</h1>
            <form method="post">
                <div class="form-group mb-4">
                    <label for="first_name">First Name:</label>
                    <input class ="form-control" type="text" id="first_name" name="first_name" required>
                </div>
                <div class="form-group mb-4">
                    <label for="last_name">Last Name:</label>
                    <input class ="form-control" type="text" id="last_name" name="last_name" required>
                </div>
                <div class="form-group mb-4">
                    <label for="email">Email:</label>
                    <input class ="form-control" type="email" id="email" name="email" required>
                </div>
                <div class="form-group mb-4">
                    <label for="date">Available Start Date:</label>
                    <input class ="form-control" type="date" id="date" name="date" required>
                </div>
                <div class="form-group mb-4">
                    <label>Current Occupation:</label>
                    <br>
                    <div class="btn-group-vertical" id="occupation">
                        <input class="btn-check form-control" type="radio" id="employed" name="occupation" value="employed" required>
                        <label class="btn btn-outline-secondary" for="employed">Employed</label>

                        <input class="btn-check form-control" type="radio" id="unemployed" name="occupation" value="unemployed" required>
                        <label class="btn btn-outline-secondary" for="unemployed">Unemployed</label>

                        <input class="btn-check form-control" type="radio" id="self_employed" name="occupation" value="self-employed" required>
                        <label class="btn btn-outline-secondary" for="self_employed">Self-Employed</label>

                        <input class="btn-check form-control" type="radio" id="student" name="occupation" value="student" required>
                        <label class="btn btn-outline-secondary" for="student">Student</label>
                    </div>
                </div>
                <button class="btn btn-secondary mb-4" type="submit">Submit</button>
                {% if messages %}
                {% with messages = get_flashed_messages() %}
                <div class="alert alert-success">
                    {% for message in messages %}
                        {{ message }}
                    {% endfor %}
                </div>
                {% endwith %}
                {% endif %}
            </form>
        </div>
        <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    </body>
</html>

我尝试过的解决方法:

  • 移除了HTML中的脚本代码
  • 调整过表单变量的写法
  • 尝试为GET请求单独处理逻辑,但调试时发现每次刷新页面都会发送POST请求

备注:内容来源于stack exchange,提问作者Violet Ori

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 16:34:37