Archie
Archie

Reputation: 83

Upload file in flask with other form elements fails with 400 error

Getting a 400, when trying to upload a file ad send other form elements to flask from html. Tried to use ajax, but that throws me an error as well.

Python:

@app.route('/prod_diff_result', methods=['POST', 'GET'])
def prod_diff_result():

    try:
         host = request.form['host-prod-iterator']
         print(host)
         if request.files['file']:
            f = request.files['file']
            f.save(secure_filename(f.filename))

HTML:

<div class="main-div">
    <form action="/prod_diff_result" method="POST" enctype="multipart/form-data">
        <div class="grid-container">
            <div class="grid-item">
                <span class="label label-default ">PROD</span><br>
                <p>Iterator Host : <input type="text" class="form-control" id="host-prod-iterator" value="10.47.7.57"
                        required></p>

                <input type="radio" name="data_fetch_type" value="file" onclick="showfile()">Upload File
                <input type="file" name="file" />
                <input type="radio" name="data_fetch_type" value="db"> Get from DB
                <input type="submit" />
            </div>
    </form>
</div>

I want to be able send hostname and file back to flask error in one request and using one form.

Upvotes: 1

Views: 50

Answers (1)

Halvor Holsten Strand
Halvor Holsten Strand

Reputation: 20536

It gives an error because you try to access a form field that it cannot find, and assumes that somehow the request was bad, because it didn't include a required form field. You are trying to access:

host = request.form['host-prod-iterator']

However you have simply not given it a name in your HTML. If you give it a name, it should work:

<p>Iterator Host : 
    <input type="text" class="form-control" name="host-prod-iterator" id="host-prod-iterator" value="10.47.7.57" required>
</p>

Upvotes: 1

Related Questions