【问题标题】:Using select class with Flask [duplicate]将选择类与 Flask 一起使用 [重复]
【发布时间】:2021-01-22 20:33:08
【问题描述】:

我想在我的 python 应用程序中检索 html/javascript 表单中的选定值。

这是我的 html 代码:

{% block content %}
<form method="post">
   <div class="form-group">
       <label for="title">Numéro</label>
       <input type="number" name="NUMERO"
              placeholder="666, etc" class="form-control" required
              value="{{ request.form['NUMERO'] }}"/>
   </div>
<div class="form-group">
       <label for="TYPE_VOIE">Type voie</label>
       <select class="form-control" id="TYPE_VOIE" required >
          <option>Rue</option>
          <option>Impasse</option>
          <option>Place</option>
          <option>Boulevard</option>
          <option>Avenue</option>
      </select>  value="{{ request.form['TYPE_VOIE'] }}"
</div>

这里是python代码:

    if request.method == 'POST':
        numero=int(request.form['NUMERO'])
        type_voie= request.form['TYPE_VOIE'] 

现在是错误信息:

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: 浏览器 (或代理)发送了此服务器无法理解的请求。 KeyError: 'TYPE_VOIE' ...

其实我也不知道放哪里value="{{ request.form['TYPE_VOIE'] }}"

你能帮帮我吗? 提前致谢

【问题讨论】:

  • 您好像忘记了&lt;/form&gt;...?
  • 为了防止在调试成功后发生这种情况,您可以使用request.form.get("TYPE_VOIE"),它不会崩溃,只需返回None
  • 你的value="{{ request.form["TYPE_VOIE"] }}" 应该是select 标签的一个属性(如果你想要它的话),所以应该去classid 属性去的地方。

标签: forms flask bootstrap-4


【解决方案1】:

您应该像为文本框所做的那样向组合框添加 name 属性,因此:

<select class="form-control" id="TYPE_VOIE" name="TYPE_VOIE" required >

基本上,Flask 不会在您的 POST 请求中“看到”名为“TYPE_VOIE”的表单字段。

【讨论】:

  • 非常感谢....在我的表单中,我要删除所有属性 value="..." 吗?
  • 相反,如果您想在 POST 请求中检索它们的值,则应该为所有表单字段设置值标签。
猜你喜欢
  • 2014-08-16
  • 1970-01-01
  • 2021-09-25
  • 2021-09-01
  • 1970-01-01
  • 2013-06-19
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
相关资源
最近更新 更多