我正在使用 Flask 运行网站,每次我尝试提交表单并将其写入 csv 文件时,都会收到“方法不允许错误”。
这是代码的 HTML 部分:
<footer id="footer">
<section>
<form method="post" action="/generic">
<div class="fields">
<div class="field">
<label for="name">Name/Organization</label>
<input type="text" name="name" id="name" />
</div>
<div class="field">
<label for="email">Email</label>
<input type="text" name="email" id="email" />
</div>
<div class="field">
<label for="message">message</label>
<input type="text" name="message" id="message" />
</div>
</div>
<ul class="actions">
<li><input type="submit" value="Send Message" /></li>
</ul>
</form>
这是 Flask Python 服务器的一部分:
def write_to_csv(data):
with open('database.csv', mode='a',newline='') as database2:
name = data['name']
email = data['email']
message = data['message']
csv_writer = csv.writer(database2, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
csv_writer.writerow([name,email,message])
@app.route('/generic', methods=['GET', 'POST'])
def submit_form():
print("You have reached the right place")
if request.method == 'POST':
try:
data = request.form.to_dict()
write_to_csv(data)
return redirect('/generic.html')
except Exception as e:
print(e)
return 'Something went wrong, It did not save in the data base'
else:
return render_template('generic.html')
这一切都发生在 index.html 文件中,直到提交表单并且应该重定向到 generic.html 文件。但我找不到 URL:(http://127.0.0.1:5000/generic)
我是一名自学成才的 Python 程序员,我一直想知道如何创建网站,但我已经在这里停留了一段时间,而且我不熟悉 HTML,所以我尝试更改提交表单的操作以及@app.route("submit_form") 没有运气。感谢您提前提供的任何帮助:)
您似乎想在发布表单数据后再次显示同一页面。那么就不需要重定向了。像这样的事情应该做。
render_template
将在处理可选的 POST 数据后运行。正确的缩进当然至关重要。
@app.route('/generic', methods=['GET', 'POST'])
def submit_form():
print("You have reached the right place")
if request.method == 'POST':
try:
data = request.form.to_dict()
write_to_csv(data)
except Exception as e:
print(e)
return 'Something went wrong, It did not save in the data base'
return render_template('generic.html')
在页面中添加条件消息会更加方便用户使用。
此外,您可以这样做,而不是在 Jinja 模板中对 URL 进行硬编码:
<form method="post" action="{{ url_for('submit_form') }}">
然后,Jinja 将根据该
submit_form
函数的路由定义生成 URL。好处之一是,如果您在 Python 代码中重命名路由,只要匹配函数未重命名,模板就会继续工作。