Search code examples
formsflaskbad-request

Flask forms. Bad Request


I have two forms in my html. The first works correctly. The second returns Bad Request The browser (or proxy) sent a request that this server could not understand html:

<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <form method="post" >
        <input type="text" name="ssid">
        <input type="password" name="password">
        <input type="submit" value="Connect">
        </form>
        <form method="post" >
        <input type="hidden" name="ind" value="1">
        <input type="submit"  value="Disconnect">
        </form>
    </body>
</html>

Python:

@app.route('/', methods=['POST'])
@app.route('/index', methods=['POST'])
def wifi_form():
    wifi_ssid=request.form['ssid']
    wifi_pass=request.form['password']
    result='Connect'
    return result
@app.route('/', methods=['POST'])
@app.route('/index', methods=['POST'])
def del_form():
    ind=request.form['ind']
    result='disconnect'
    return result

Solution

  • I think you are taking the wrong approach. Index page will pop up when you start your localserver, also the form in which you are expecting result will only come after the user enters the values, your routes are all messed up. PLease refer to the doc here.. https://scotch.io/tutorials/getting-started-with-flask-a-python-microframework

    I am reformatting the code a bit for you.. hope this helps

    main.py

    from flask import Flask, render_template, request
    
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        return render_template('main.html')
    
    @app.route('/wifi_form', methods=['POST'])
    def wifi_form():
        wifi_ssid=request.form['ssid']
        wifi_pass=request.form['password']
        result='Connect'
        return render_template('main.html', result=result)
    
    @app.route('/del_form', methods=['POST'])
    def del_form():
        ind=request.form['ind']
        result='disconnect'
        return render_template('main.html', result=result)
    

    put the below html code in templates folder in the same dir

    <html>
        <head>
            <title>Test</title>
        </head>
        <body>
            <form action="{{url_for('wifi_form')}}" method="post" >
            <input type="text" name="ssid">
            <input type="password" name="password">
            <input type="submit" value="Connect">
            </form>
            <form action="{{url_for('del_form')}}" method="post" >
            <input type="hidden" name="ind" value="1">
            <input type="submit"  value="Disconnect">
            </form>
    
          {% if result %}
               {{ result }}
         {% endif %}    
    
        </body>
    </html>