在阅读了许多类似的发音问题和相关的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。我还查询了数据库,并确认未添加表单中的其他内容。
GET
POST
from flask import request
在Flask应用程序中,我请求的表单字段在HTML表单中被标记为略有不同。
该解决方案很简单,并且在评论中没有发现。正如这个问题所解决的,表单发送错误Flask,由Sean Vieira指出,
…问题是Flask在args中找不到键并形成字典时会引发HTTP错误。Flask默认情况下假设的是,如果你要的是特定密钥,而该密钥不存在,则请求中遗漏了某些内容,并且整个请求均无效。
换句话说,如果在HTML中仅找不到你在Python中请求的一个表单元素,则POST请求无效并且出现错误,在我的情况下,回溯中没有任何异常。对我来说,拼写缺乏一致性:在HTML中,我标记了各种表单输入
<input name="question1_field" placeholder="question one">
在Python中,当有一个POST调用时,我抓取了一个不存在的表单
request.form['question1']
但是,为了与我的HTML表单名称保持一致,
request.form['question1_field']
我希望这有帮助。