AkademiLegi
AkademiLegi

Reputation: 27

How to set variables with a inputbox in Flask

I want to declare variables in Flask using input boxes.

However, I get this error message:

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

But i cleary named my inputbox...

My Flask code app.py :

@app.route('/', methods=['POST', 'GET'])
def get_columns():
    col1 = request.form["column1"]
    col2 = request.form["column2"]
    return col1, col2

def upload_file():
    file = request.files['file']
    col1,col2 =get_columns()

    print("file:",file)

    if file.filename == '':
        flash('No file selected for uploading','red')
        # return redirect(request.url)
        return render_template('index.html', disp_div = disp_div)
    if file and allowed_file(file.filename):
        df=pd.read_csv(file)
        output=col1,col2,df["Age"].mean().round(2)
        return render_template('index.html', output=output)
        # return redirect('/')
    else:
        flash('Allowed file types are txt, pdf, png, jpg, jpeg, gif', 'red')
        # return redirect(request.url)
        return render_template('index.html')

My jinja template index.html:

...
          <tr>
              <td><form action="/" method="POST">
                      <input name="column1" id="column1" placeholder="Spaltenname der XXX">
                  </form>
              </td>

              <td><form action="/" method="POST">
                        <input name="column2" id="column2" placeholder="Spaltenname der YYY">
                  </form>
              </td>
          </tr>
....

Upvotes: 0

Views: 53

Answers (1)

balderman
balderman

Reputation: 23825

You have 2 forms in your HTML. Both of them point to get_columns().
But the python code assume it will get both of them (column1 AND column2).
This is wrong - the python code will get column1 OR column2 - not both.

Upvotes: 1

Related Questions