在阅读了许多类似的听起来问题和相关的 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
or POST
,但我在这两个函数中都这样做了,我仔细检查以确保我导入了所有必要的东西,例如from flask import request
. 我还查询了数据库并确认没有添加表单中的添加内容。
在 Flask 应用程序中,我请求的表单字段在 HTML 表单中的标记略有不同。保持名称一致是必须的。更多可以在这个问题中阅读表单发送错误,烧瓶