Question

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.

Was it helpful?

Solution

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...

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top