我的网站表单在提交后总是发送POST请求,甚至在重新加载网页后,导致数据库重复

问题描述 投票:0回答:1

在网站中提交表单时,它会保存提交后输入的数据,如果您重新加载或重新打开网站,它会发送POST请求,然后立即将相同的数据发送到数据库。

这是我的代码: 蟒蛇

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/[email protected]/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/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    </body>
</html>

我尝试删除html中的脚本,表单变量,我还尝试使用“GET”的request.method,但是在尝试调试程序时,每次重新加载网站时它总是发送一个“POST”请求。

python html flask
1个回答
0
投票

为了从表单发送不同类型的请求,您需要更改 HTML 中的

method
属性: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form

我不太确定为什么您的表单被多次提交(也许尝试在提交时清除表单),但您的数据库和 API 可能不允许您创建多个记录。

我会在表中的电子邮件字段上创建一个唯一约束,并在创建新记录之前添加一个检查,以确保不存在具有该电子邮件的用户。

© www.soinside.com 2019 - 2024. All rights reserved.