烧瓶,为什么request.form运行错误400?

时间:2020-08-03 23:51:03

标签: python html flask

我正在尝试从以下HTML代码中提取文本:

@app.route("/", methods=['GET', 'POST'])
def home():
  if request.method == 'POST':
    H_desiderata = float(request.form.get('H_desiderata')) #THIS CAUSES THE ERROR
    return render_template('form1.html')

以下HTML:

    <body>
      <h2>Brioche Recipe</h2>
        <form>
          <div class="grid-container">
            <div class="grid-item">
      
              <label class="text" for="H_desiderata">
              H_desiderata:
               </label><be>
               <input type="number" id="H_desiderata" name="H_desiderata1" 
               value={{val_H_desiderata}} min="1" max="99" step="1"><br>

在将其放入网格之前,它可以正常工作:

enter image description here

旧的工作代码:

<form>
  <label for="H_desiderata">H_desiderata:</label><br>
    <input type="number" id="H_desiderata" name="H_desiderata" 
    value={{val_H_desiderata}} min="1" max="99" step="1"><br>

如何修改request.form以在输入框中返回值?

1 个答案:

答案 0 :(得分:1)

您的代码有很多错误,但让我们从这里开始:

request.form

request.method == "GET为空。所以。 request.form['H_desiderata']会给出关键错误。

将其移动到视图的POST部分。另外,如果未定义,请使用request.form.get('H_desiderata', -9999999)

更新:

好,现在尝试:

if request.method == 'POST':
    print(request.form)
    print(request.form.get('H_desiderata'))
    print(float(request.form.get('H_desiderata')))
    H_desiderata = float(request.form.get('H_desiderata'))

然后,您将要:

return render_template('form1.html', val_H_desiderata=H_desiderata)

UPDATE2:

您的<form>标签格式错误。试试:

<form action="/" method="post">

UPDATE3:

您更改了输入的名称,因此更改为:request.form.get('H_desiderata1')