简体   繁体   中英

How can I make html submit button functional in flask?

I have a Flask application, and in my html template (which is Jinja2) I have a simple form which has only a button:

<form name='resetLayoutForm' method='POST'>
    <input type="submit" value="Reset layout" class="submitButton"/> 
</form>

Now, I want to know how can I 'let the Python script know' that the button was clicked?

I tried with:

@app.route('/localhost/some_route', methods = ['POST', 'GET'])
def function():
    .   .    .
    if request.method == 'POST':
        # code
    .   .    .

but this isn't a good solution, because I have some other operations in the code that are using the POST request method, and I don't want #code to be activated when I use these other POST operations.

Duplicate the form that contains the button and set it's action to a different URL. Then, when pressed, only that different URL will receive the data.

Obviously, as others have noted, there are Javascript mechanisms to achieve this but if those are not needed...

What do you mean by "'let the Python script know' that the button was clicked?"

If you don't want to talk to the server and the button click is only for client side, then why not use Javascript ? For example, the simplest way would be to use the onclick event :

<input type="submit" value="Reset layout" class="submitButton" onclick=doSomething() />

where doSomething() is a javascript function you can write

You can check for the input's value attribute with request.form.values() as such:

@app.route('/localhost/some_route', methods = ['POST', 'GET'])
def function():
    # code
    if 'Reset_layout' in request.form.values():
        # code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM