getting drop down menu Data on Flask via form is giving 400 Bad Request

Viewed 9590

Here is the html and flask python code. When user select Audi from drop down menu I wanted that it give the Done as answer. I am getting 400 bad request error.

form.html

<!DOCTYPE html>
 <html>
 <body>

<p>Select a new car from the list.</p>
<form id="form1" action="/login" method="GET" enctype="multipart/form-data">
<select id="mySelect" name = "cars">
  <option value="Audi">Audi</option>
  <option value="BMW">BMW</option>
  <option value="Mercedes">Mercedes</option>
  <option value="Volvo">Volvo</option>
</select>
</form>
<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>

</body>
</html>

app.py

from flask import Flask, render_template, redirect, url_for,request
from flask import make_response

app = Flask(__name__)

@app.route('/login', methods=['GET','POST'])
def login():
    c=str((request.form['cars']))
    print(c)
    if(c == "Audi"):
           print("Done")
    return render_template('form.html')
1 Answers

Use of print in route will not affect the template. You need to pass a variable with to the template while rendering.

And as you intend to use multipart/form-data you might need to use POST method.

I am showing a scenario which you can modify as per your requirement.

app.py contains:

from flask import Flask, render_template, request, url_for, redirect

app = Flask(__name__)

@app.route('/')
@app.route('/index')
def index():
    return render_template("dropdown.html")

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == "POST":
        car_brand = request.form.get("cars", None)
        if car_brand!=None:
            return render_template("dropdown.html", car_brand = car_brand)
    return render_template("dropdown.html")

if __name__ == '__main__':
    app.run(debug=True)

dropdown.html contains a simple select tag with a submit button and to show the selected value:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="author" content="Ahmedur Rahman Shovon">
    <title>Dropdown Example</title>
</head>
<body>
  <p>Select a new car from the list.</p>
  <form id="form1" action="/login" method="POST" enctype="multipart/form-data">
    <select id="mySelect" name = "cars">
      <option value="Audi">Audi</option>
      <option value="BMW">BMW</option>
      <option value="Mercedes">Mercedes</option>
      <option value="Volvo">Volvo</option>
    </select>
    <input type="submit" value="Submit">
  </form>
  <p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
  <div id="result">
    {% if car_brand is defined %}
        You have selected: {{ car_brand }}
    {% endif %}
  </div>
</body>
</html>

Output:

dropdown demo

Related