如何在Flask中获取提交表单的名称? [英] How to get the name of a submitted form in Flask?

查看:1241
本文介绍了如何在Flask中获取提交表单的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Flask构建一个网站,在一个页面上我有两个表单。如果有POST,我需要决定发布哪个表单。我当然可以从 request.form 中的字段中扣除它,但我宁愿通过获取名称来定义它(由提交表单的< form name =my_form> )。我尝试了几件事情,比如:

$ $ $ $ $ $ $ $ $ $ app.route('/ myforms',methods = ['GET',' POST'])
def myForms():
if request.method =='POST':
print request.form.name
print request.form。['name' ]

但不幸的是,没有任何作用。有谁知道我可以在哪里得到提交的表格的名称?所有的提示都是值得欢迎的!

解决方案

没有表单名称。该信息不是由浏览器发送的; < form> 标签上的名称属性仅用于浏览器端(并且不推荐使用,可以使用 id )。



您可以通过隐藏 字段,但最常见的方式来区分发布到同一个表单处理程序的表单是给提交按钮的名称:

 < submit name =form1value =Submit!/> 

  if request.form中的'form1':

但是您也可以使用< input type =hidden> 字段包含区分表单的方法。

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!

解决方案

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.

这篇关于如何在Flask中获取提交表单的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆