以下是一个示例代码,展示了如何在表单中包含空回复:
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
# 获取表单数据
name = request.form.get('name')
email = request.form.get('email')
message = request.form.get('message')
# 检查表单是否为空
if not name or not email or not message:
return render_template('index.html', error='请填写完整的表单')
# 处理表单数据
# ...
return render_template('success.html')
return render_template('index.html')
if __name__ == '__main__':
app.run()
上述代码使用了 Flask 框架,创建了一个简单的 Web 应用。当用户访问网站首页时,会显示一个表单。用户填写表单并提交后,服务器会接收到 POST 请求,获取表单数据。然后,代码会检查表单数据是否为空。如果有任何一个字段为空,就会返回带有错误信息的模板(index.html),否则处理表单数据并返回成功页面(success.html)。
在模板文件(index.html)中,可以添加以下代码来显示错误信息:
{% if error %}
{{ error }}
{% endif %}
这样,如果表单有空字段,就会在页面上显示错误信息。