Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the name of a submitted form in Flask?

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!

like image 373
kramer65 Avatar asked Oct 06 '14 13:10

kramer65


People also ask

How do you access form fields in flask?

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

How do you handle form submit in flask?

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.


1 Answers

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.

like image 138
Martijn Pieters Avatar answered Oct 29 '22 16:10

Martijn Pieters