11

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!

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
kramer65
  • 50,427
  • 120
  • 308
  • 488

1 Answers1

24

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks! That indeed solves my problem! I never knew that wasn't sent by the browser. One last question: what do you mean with "deprecated to boot"? – kramer65 Oct 06 '14 at 14:02
  • @kramer65: the `name` attribute has been deprecated in HTML 4. So not only isn't it useful for your use case, it is not even an attribute you should be using anymore. – Martijn Pieters Oct 06 '14 at 14:03
  • Ah, awesome. I learned html in the nineties, after which I mainly worked in backend systems for years. So my html skills are a bit dated.. ;) Thanks a million! – kramer65 Oct 06 '14 at 14:11
  • Yeah, but how can you distinguish between two submit buttons when you have 2 submit buttons in Flask like so: `form.submit(class="btn btn-outline-info")`. Where can I specify the name attribute here? – KeyC0de Dec 09 '19 at 23:32
  • @Nikos: if you have a `form.submit` attribute that is a submit field, then it is named `submit`. If you have multiple submit fields, they each have their own name *already*. The name for each comes from the attribute name you used when you created the fields: `fieldname = SubmitField(...)`. – Martijn Pieters Dec 12 '19 at 19:04
  • @MartijnPieters You're saying that the 'name' attribute is the variable fieldname? In other words in Flask forms your `fieldname = SubmitField(...)` is equal to, in HTML, ``? – KeyC0de Dec 12 '19 at 19:18
  • 1
    @Nikos: yes, exactly. WTForms always adds the bound fieldname to input fields as the `name` attribute, submit is no exception. – Martijn Pieters Dec 12 '19 at 19:41