最佳答案
在阅读了许多类似的声音问题和相关的 Flask 文档之后,我似乎无法弄清楚是什么导致了提交表单时出现以下错误:
400个错误请求
浏览器(或代理)发送了此服务器无法理解的请求。
虽然表单总是正确显示,但当我提交一个绑定到这两个函数之一的 HTML 表单时,会发生错误请求:
@app.route('/app/business', methods=['GET', 'POST'])
def apply_business():
if request.method == 'POST':
new_account = Business(name=request.form['name_field'], email=request.form['email_field'], account_type="business",
q1=request.form['q1_field'], q2=request.form['q2_field'], q3=request.form['q3_field'], q4=request.form['q4_field'],
q5=request.form['q5_field'], q6=request.form['q6_field'], q7=request.form['q7_field'],
account_status="pending", time=datetime.datetime.utcnow())
db.session.add(new_account)
db.session.commit()
session['name'] = request.form['name_field']
return redirect(url_for('success'))
return render_template('application.html', accounttype="business")
@app.route('/app/student', methods=['GET', 'POST'])
def apply_student():
if request.method == 'POST':
new_account = Student(name=request.form['name_field'], email=request.form['email_field'], account_type="student",
q1=request.form['q1_field'], q2=request.form['q2_field'], q3=request.form['q3_field'], q4=request.form['q4_field'],
q5=request.form['q5_field'], q6=request.form['q6_field'], q7=request.form['q7_field'], q8=request.form['q8_field'],
q9=request.form['q9_field'], q10=request.form['q10_field'],
account_status="pending", time=datetime.datetime.utcnow())
db.session.add(new_account)
db.session.commit()
session['name'] = request.form['name_field']
return redirect(url_for('success'))
return render_template('application.html', accounttype="student")
HTML 的相关部分是
<html>
<head>
<title>apply</title>
</head>
<body>
{% if accounttype=="business" %}
<form action="{{ url_for('apply_business') }}" method=post class="application_form">
{% elif accounttype=="student" %}
<form action="{{ url_for('apply_student') }}" method=post class="application_form">
{% endif %}
<p>Full Name:</p>
<input name="name_field" placeholder="First and Last">
<p>Email Address:</p>
<input name="email_field" placeholder="your@email.com">
...
对于大多数人来说,问题不在于调用 GET
或 POST
,但是我在这两个函数中都这样做了,并且我进行了双重检查以确保导入了所有必要的内容,比如 from flask import request
。我还查询了数据库,并确认没有添加表单中的内容。
在 Flask 应用程序中,我请求的表单字段在 HTML 表单中的标签略有不同。保持名称的一致性是必须的。更多内容可以阅读这个问题 表单发送错误,烧瓶