Flask request.form returns an error with 2 different types of input

47 Views Asked by At

I've seen few posts about this error, but none of them helped me with my case. index.html

<p><input type="number" step="0.01" name="data_split" value="0.2">DATA_SPLIT</p>

<select name="kusy" id="" >
  <option value="gini" selected= "{{ val2 == 'gini' }}">Gini</option>
  <option value="entropy" selected= "{{ val2 == 'entropy' }}">Entropy</option>
</select>

main.py

if request.method == 'POST': 
    if (len(request.form['data_split']) > 0):    
        text = request.form['data_split']
        train_test_data_split = float(text)
    else: 
        train_test_data_split = 0.2    
else: 
    train_test_data_split = 0.2


if request.method == 'POST': 
    if (len(request.form['kusy']) > 0):    
        text = request.form['kusy']
        criterion = text
    else: 
        criterion = 'gini'    
else: 
    criterion = 'gini'

Error message

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'kusy'

The problem with this form is that, it works only if I have one of those input types e.g.

  • 2 inputs of type number will work
  • 2 inputs of type select will work
  • 1 input of type number and 1 input of type select will throw an error

Troubleshooting I've done:

  • tried to change request.form to request.form.get, but I run into more errors -> If this is fastest solution I'm willing to try again
  • made sure all values from HTML's name don't have typos

I'm looking for a quick fix if possible.

That's the whole and only form that exists.

  <form method="post">
<p><input type="number" step="0.01" name="data_split" value="0.2">DATA_SPLIT</p>

<select name="kusy"  >
  <option value="gini" selected= "{{ val2 == 'gini' }}">Gini</option>
  <option value="entropy" selected= "{{ val2 == 'entropy' }}">Entropy</option>
</select>
<select name="output_column"  >
  <option value="Pclass" selected= "{{ val3 == 'Pclass' }}">Pclass</option>
  <option value="Sex" selected= "{{ val3 == 'Sex' }}">Sex</option>
  <option value="Age" selected= "{{ val3 == 'Age' }}">Age</option>
  <option value="Parch" selected= "{{ val3 == 'Parch' }}">Parch</option>
  <option value="Embarked" selected= "{{ val3 == 'Embarked' }}">Embarked</option>
  <option value="Title" selected= "{{ val3 == 'Title' }}">Title</option>
  <option value="FareBand" selected= "{{ val3 == 'FareBand' }}">FareBand</option>
</select>
<select name="splitting" >
  <option value="best" selected= "{{ val4 == 'best' }}">Best</option>
  <option value="random" selected= "{{ val4 == 'random' }}">Random</option>
</select>

<p><input type="text" name="work" min="1" max="8" value="3">MAX_Depth</p>
<input type="submit">
0

There are 0 best solutions below