kramer65
kramer65

Reputation: 53843

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!

Upvotes: 12

Views: 23280

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121266

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.

Upvotes: 25

Related Questions