在阅读了许多类似的听起来问题和相关的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表单中被标记为略有不同。必须保持名称一致。有关此问题的更多信息,请阅读表格发送错误,烧瓶