dexter February 2016

Flask/Python - handling dropdown to open different HTML pages

I'm learning flask and Python along with HTML and CSS. I've got a Flask template to render a dropdown.

What I need to do is this: When you select a value from the dropdown it opens a new HTML page corresponding to the value chosen(different page for different options chosen).

I tried searching the web but couldn't get much resources. When I submit the dropdown option by submit button the page gives a error message saying:

Method Not Allowed

The method is not allowed for the requested URL.

Please guide me to the best possible solution.

Below is my code.

pro.html

    <form name="startpage" method="POST" action="">
    <div class="form-group">
        <div class="input-group">
            <select name = "method_cipher" id = "method_cipher"> 
                <option value="Encrypt">Encrypt</option>
                <option value="Decrypt">Decrypt</option>
            </select>
            <select name = "cipher_type" id = "cipher_type"> 
                <option value="Caesar">Caesar</option>
                <option value="Transposition">Transposition</option>
                <option value="Reverse">Reverse</option>
            </select>
        </div>
        <button type="submit" name="submit" value="success" class="btn btn-default">Submit</button>
    </div>
    </form> 

test.py

    import flask
    APP = flask.Flask(__name__)
    @APP.route('/')
    def index():
        return flask.render_template('pro.html')
    @APP.route("/test" , methods=['GET', 'POST'])
    def test():
        if flask.request.method == 'POST':
            select = flask.request.form.get('method_cipher')
            if(select == 'Encrypt'):
                return flask.render_template('lastpage.html')
    if __name__ == '__m        

Answers


Wombatz February 2016

Your form in pro.html sends the data to the url specified by the action attribute. If you leave that out or set it to an empty string like you did the requests goes to the same page which is /.

But you already set up the form handling in a different view function. You probably want to post to that one.

So change your form to post to the correct url

<form ... action="/test" ...>

That will work but it is not a good idea to hardcode the target url in the template. I assume you are using jinja so you can let it insert the url for you

<form ... action="{{ url_for("test") }}" ...>

Take a look at the url_for function if you haven't already.

Post Status

Asked in February 2016
Viewed 2,582 times
Voted 12
Answered 1 times

Search




Leave an answer