I'm building a website using Flask, and on one page I've got two forms. If there's a POST, I need to decide which form is being posted. I can of course deduct it from the fields that are present in request.form
, but I would rather make it explicit by getting the name (defined by <form name="my_form">
) of the form that is submitted. I tried several things, such as:
@app.route('/myforms', methods=['GET', 'POST'])
def myForms():
if request.method == 'POST':
print request.form.name
print request.form.['name']
but unfortunately, nothing works. Does anybody know where I can get the name of the form submitted? All tips are welcome!
You can get form data from Flask's request object with the form attribute: from flask import Flask, request app = Flask(__name__) @app. route('/', methods=['GET', 'POST']) def index(): data = request. form['input_name'] # pass the form field name as key ...
When a user fills in the web form and clicks the Submit button, a POST request gets sent to the /create route. There you handle the request, validate the submitted data to ensure the user has not submitted an empty form, and add it to the messages list.
There is no 'name of the form'. That information is not sent by the browser; the name
attribute on <form>
tags is meant to be used solely on the browser side (and deprecated to boot, use id
instead).
You could add that information by using a hidden field, but the most common way to distinguish between forms posting to the same form handler is to give the submit button a name:
<submit name="form1" value="Submit!"/>
and
if 'form1' in request.form:
but you could also use a <input type="hidden">
field to include the means to distinguish between forms.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With