简体   繁体   中英

Flask, why does request.form runs error 400?

I am trying to extract text from the following HTML code:

@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 below:

    <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>

Before putting it into a grid it worked:

在此处输入图像描述

old working code:

<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>

How should I adapt request.form to return the value within the input box?

There is so much wrong with your code, but let's start with this:

request.form is empty when request.method == "GET . So. request.form['H_desiderata'] will give a key error.

Move that to the POST section of your view. Also, use request.form.get('H_desiderata', -9999999) in case it's not defined.

UPDATE:

OK, now try:

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'))

Then, you are going to want:

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

UPDATE2:

Your <form> tag is malformed. Try:

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

UPDATE3:

You change the name of the input, so change to: request.form.get('H_desiderata1')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM