我想将表单数据从html页面发送到我的后端python代码,并将详细信息存储在数据库中。但是,当我提交表单时,我的数据库保持不变。我在后端使用flask与flask_mysqldb进行数据库。 这是我的python代码:
from flask import Flask,render_template,request,json
from flask_mysqldb import MySQL
import requests
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'CUCTOMER_MESSAGES'
mysql = MySQL(app)
@app.route('/', methods=['GET', 'POST'])
def home():
if request.method == "POST":
Name = request.form['name']
Email = request.form['email']
Phone = request.form['phone']
Message = request.form['message']
print(request.form)
cur = mysql.connection.cursor()
sql = 'INSERT INTO MyUsers(Name,Email,Phone,Message) VALUES (%s,%s,%s,%s);'
cur.execute(sql,(Name,Email,Phone,Message))
mysql.connection.commit()
cur.close()
return render_template('index.html')
if __name__ == '__main__':
app.run()
这是我的html表单:
<form action="" method="post" class="needs-validation" novalidate>
<p><small>Select A Service</small></p>
<div class="row">
<div class="col">
<select name="enquiry" class="custom-select mb-3">
<option selected>General Enquiry</option>
<option value="wedding">Wedding Planner</option>
<option value="photography">Photography</option>
<option value="catering">Catering</option>
<option value="decor">Decoration</option>
<option value="event">Event Management</option>
</select>
<textarea class="form-control" rows="4" placeholder="Tell Us About Your Request" name="message" required></textarea>
</div>
<div class="col">
<input type="text" class="form-control" placeholder="Enter Your Name" name="name" required><br>
<input type="email" class="form-control" placeholder="Enter Your E-mail" id="email" required><br>
<input type="tel" class="form-control" name="phone" placeholder="Enter Your Phone Number" required>
</div>
</div><br>
<div class="container">
<div class="row">
<div class="col text-center">
<button type="submit" class="btn btn-outline-dark">Send Message</button>
<p><small><br>Please note that Wedding Amigos may not be able to honour all booking requests made.</small></p>
</div>
</div>
</div><br><br>
</form>
我该怎么办?
答案 0 :(得分:2)
您的表单向服务器发送了错误的请求。您的input
标签
<input type="email" class="form-control" placeholder="Enter Your E-mail" id="email" required>
不包含name
属性。因此,发送到服务器的表单缺少电子邮件地址,这会导致您所在行的异常
Email = request.form['email']
由于在执行查询之前发生了异常,所以数据库中没有任何更改。