89

我在同一页面上有多个表单,它们将发布请求发送到烧瓶中的同一处理程序。

我正在使用 wtforms 生成表单。

确定提交哪种表格的最佳方法是什么?

我目前正在使用action="?form=oneform". 我认为应该有一些更好的方法来实现相同的目标?

4

8 回答 8

100

上面的解决方案有一个验证错误,当一个表单导致验证错误时,两个表单都会显示错误消息。我改变顺序if来解决这个问题。

首先,SubmitField使用不同的名称定义您的倍数,如下所示:

class Form1(Form):
    name = StringField('name')
    submit1 = SubmitField('submit')

class Form2(Form):
    name = StringField('name')
    submit2 = SubmitField('submit')

....

然后在中添加一个过滤器view.py

....
form1 = Form1()
form2 = Form2()
....

if form1.submit1.data and form1.validate(): # notice the order 
....
if form2.submit2.data and form2.validate(): # notice the order 
....

现在问题解决了。

如果您想深入了解它,请继续阅读。

这里是validate_on_submit()

def validate_on_submit(self):
    """
    Checks if form has been submitted and if so runs validate. This is
    a shortcut, equivalent to ``form.is_submitted() and form.validate()``
    """
    return self.is_submitted() and self.validate()

这是is_submitted()

def is_submitted():
    """Consider the form submitted if there is an active request and
    the method is ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.
    """
    return _is_submitted()  # bool(request) and request.method in SUBMIT_METHODS

当您调用form.validate_on_submit()时,无论单击哪个提交按钮,它都会检查表单是否通过 HTTP 方法提交。所以上面的小技巧只是添加一个过滤器(检查提交是否有数据,即,form1.submit1.data)。

此外,我们改变了 的顺序if,所以当我们点击一​​个提交时,它只调用validate()这个表单,防止两个表单的验证错误。

故事还没有结束。这里是.data

@property
def data(self):
    return dict((name, f.data) for name, f in iteritems(self._fields))

它返回一个带有字段名称(键)和字段数据(值)的字典,但是,我们的两个表单提交按钮具有相同的名称submit(键)!

当我们单击第一个提交按钮(在 form1 中)时,来自的调用form1.submit1.data返回一个像这样的字典:

temp = {'submit': True}

毫无疑问,当我们调用时if form1.submit.data:,它会返回True

当我们点击第二个提交按钮(在form2中)时,调用.datain if form1.submit.data:add a key-value in dict first,然后调用if form2.submit.data:add another key-value,最后,dict会是这样的:

temp = {'submit': False, 'submit': True}

现在我们调用if form1.submit.data:,它返回True,即使我们点击的提交按钮在 form2 中。

这就是为什么我们需要SubmitField用不同的名字来定义这两个。顺便说一句,感谢阅读(到这里)!

更新

还有另一种方法可以在一个页面上处理多个表单。您可以使用多个视图来处理表单。例如:

...
@app.route('/')
def index():
    register_form = RegisterForm()
    login_form = LoginForm()
    return render_template('index.html', register_form=register_form, login_form=login_form)

@app.route('/register', methods=['POST'])
def register():
    register_form = RegisterForm()
    login_form = LoginForm()

    if register_form.validate_on_submit():
        ...  # handle the register form
    # render the same template to pass the error message
    # or pass `form.errors` with `flash()` or `session` then redirect to /
    return render_template('index.html', register_form=register_form, login_form=login_form)


@app.route('/login', methods=['POST'])
def login():
    register_form = RegisterForm()
    login_form = LoginForm()

    if login_form.validate_on_submit():
        ...  # handle the login form
    # render the same template to pass the error message
    # or pass `form.errors` with `flash()` or `session` then redirect to /
    return render_template('index.html', register_form=register_form, login_form=login_form)

在模板 (index.html) 中,您需要渲染两个表单并将action属性设置为目标视图:

<h1>Register</h1>
<form action="{{ url_for('register') }}" method="post">
    {{ register_form.username }}
    {{ register_form.password }}
    {{ register_form.email }}
</form>

<h1>Login</h1>
<form action="{{ url_for('login') }}" method="post">
    {{ login_form.username }}
    {{ login_form.password }}
</form>
于 2016-09-29T09:15:22.200 回答
65

我一直在使用两个烧瓶片段的组合。首先向表单添加前缀,然后使用 validate_on_submit() 检查前缀。我还使用 Louis Roché 的模板来确定在表单中按下了哪些按钮

引用丹·雅各布的话:

例子:

form1 = FormA(prefix="form1")
form2 = FormB(prefix="form2")
form3 = FormC(prefix="form3")

然后,添加一个隐藏字段(或只检查一个提交字段):

if form1.validate_on_submit() and form1.submit.data:

引用 Louis Roché 的话:

我的模板中有:

<input type="submit" name="btn" value="Save">
<input type="submit" name="btn" value="Cancel">

为了弄清楚我的views.py文件中有哪个按钮通过了服务器端:

if request.form['btn'] == 'Save':
    something0
else:
    something1
于 2013-08-17T21:34:00.500 回答
21

一种简单的方法是为不同的提交字段使用不同的名称。例如:

forms.py:</p>

class Login(Form):

    ...
    login = SubmitField('Login')


class Register(Form):

    ...
    register = SubmitField('Register')

视图.py:

@main.route('/')
def index():

    login_form = Login()
    register_form = Register()


    if login_form.validate_on_submit() and login_form.login.data:
        print "Login form is submitted"

    elif register_form.validate_on_submit() and register_form.register.data:
        print "Register form is submitted"

    ...
于 2016-03-31T09:33:50.113 回答
8

作为其他答案,我还为页面上的每个表单为每个提交按钮分配了一个唯一的名称。

然后,flask web 操作如下所示 - 注意formdataobj参数,它们有助于相应地初始化/保存表单字段:

@bp.route('/do-stuff', methods=['GET', 'POST'])
def do_stuff():
    result = None

    form_1 = None
    form_2 = None
    form_3 = None

    if "submit_1" in request.form:
        form_1 = Form1()
        result = do_1(form_1)
    elif "submit_2" in request.form:
        form_2 = Form2()
        result = do_2(form_2)
    elif "submit_3" in request.form:
        form_3 = Form3()
        result = do_3(form_3)

    if result is not None:
        return result

    # Pre-populate not submitted forms with default data.
    # For the submitted form, leave the fields as they were.

    if form_1 is None:
        form_1 = Form1(formdata=None, obj=...)
    if form_2 is None:
        form_2 = Form2(formdata=None, obj=...)
    if form_3 is None:
        form_3 = Form3(formdata=None, obj=...)

    return render_template("page.html", f1=form_1, f2=form_2, f3=form_3)


def do_1(form):
    if form.validate_on_submit():
        flash("Success 1")
        return redirect(url_for(".do-stuff"))


def do_2(form):
    if form.validate_on_submit():
        flash("Success 2")
        return redirect(url_for(".do-stuff"))

def do_3(form):
    if form.validate_on_submit():
        flash("Success 3")
        return redirect(url_for(".do-stuff"))
于 2017-09-07T21:25:43.740 回答
5

那么这是一个简单的技巧

假设你有

Form1、Form2 和索引


Form1  <form method="post" action="{{ url_for('index',formid=1) }}">

Form2  <form  method="post" action="{{ url_for('index',formid=2) }}">

现在在索引中

@bp.route('/index', methods=['GET', 'POST'])
def index():
    formid = request.args.get('formid', 1, type=int)
    if formremote.validate_on_submit() and formid== 1:
        return "Form One"
    if form.validate_on_submit() and formid== 2:
        return "Form Two"
于 2020-03-09T11:15:41.690 回答
3

我没有使用 WTForms 但无论如何都应该工作。这是一个非常快速和简单的答案;您需要做的就是为提交按钮使用不同的值。然后,您可以根据每个执行不同的 def。

index.html中:

    <div>
        <form action="{{ url_for('do_stuff')}}" method="POST">
            <h1>Plus</h1>
            <input type = "number" id = "add_num1" name = "add_num1" required><label>Number 1</label><br>
            <input type = "number" id = "add_num2" name = "add_num2" required><label>Number 2</label><br>
            <input type = "submit" value = "submit_add" name = "submit" ><br>
        </form>
        <p>Answer: {{ add }}</p>
    </div>

    <div>
        <form action="{{ url_for('do_stuff')}}" method="POST">
            <h1>Minus</h1>
            <input type = "number" id = "min_num1" name = "min_num1" required><label>Number 1</label><br>
            <input type = "number" id = "min_num2" name = "min_num2" required><label>Number 2</label><br>
            <input type = "submit" value = "submit_min" name = "submit"><br>
        </form>
        <p>Answer: {{ minus }}</p>
    </div>

app.py中:

@app.route('/',methods=["POST"])
def do_stuff():
    if request.method == 'POST':
        add = ""
        minus = ""
        if request.form['submit'] == 'submit_add':
            num1 = request.form['add_num1']
            num2 = request.form['add_num2']
            add = int(num1) + int(num2)

        if request.form['submit'] == 'submit_min':
            num1 = request.form['min_num1']
            num2 = request.form['min_num2']
            minus = int(num1) - int(num2)
    return render_template('index.html', add = add, minus = minus)
于 2019-07-29T09:49:32.470 回答
2

我通常使用作为标识符的隐藏标签。

这是一个例子:

class Form1(Form):
    identifier = StringField()
    name = StringField('name')
    submit = SubmitField('submit')

class Form2(Form):
    identifier = StringField()
    name = StringField('name')
    submit = SubmitField('submit')

然后你可以在 view.py 中添加一个过滤器:

....
form1 = Form1()
form2 = Form2()
....

if form1.identifier.data == 'FORM1' and form1.validate_on_submit():
....
if form2.identifier.data == 'FORM2' and form2.validate_on_submit():
....

最后在 HTML 中:

<form method="POST">
  {{ form1.indentifier(hidden=True, value='FORM1') }}
</form>
<form method="POST">
  {{ form2.indentifier(hidden=True, value='FORM2') }}
</form>

如果您在 if 语句中这样做,它将检查标识符是什么,如果它相等,它将运行您在代码中拥有的表单内容。

于 2020-04-26T21:37:37.240 回答
2

示例:单个 html 页面中的多个 WTForm

应用程序.py

"""
Purpose Create multiple form on single html page.

Here we are having tow forms first is Employee_Info and CompanyDetails
"""
from flask import Flask, render_template, request
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, FloatField, validators
from wtforms.validators import InputRequired

app = Flask(__name__)
app.config['SECRET_KEY'] = 'Thisisasecret'

class EmployeeInfo(FlaskForm):
    """
    EmployeeInfo class will have Name,Dept
    """
    fullName = StringField('Full Name',[validators.InputRequired()])
    dept = StringField('Department',[validators.InputRequired()])

class CompanyDetails(FlaskForm):
    """
    CompanyDetails will have yearOfExp. 
    """
    yearsOfExp = IntegerField('Year of Experiece',[validators.InputRequired()]) 


@app.route('/', methods = ['GET','POST'] )
def index():
    """
    View will render index.html page.
    If form is validated then showData.html will load the employee or company data.
    """
    companydetails = CompanyDetails()
    employeeInfo = EmployeeInfo()

    if companydetails.validate_on_submit():
        return render_template('showData.html', form = companydetails)

    if employeeInfo.validate_on_submit():
        return render_template('showData.html', form1 = employeeInfo)   

    return render_template('index.html',form1 = employeeInfo, form = companydetails)

if __name__ == '__main__':
    app.run(debug= True, port =8092)

模板/index.html

<html>
    <head>
    </head>
    <body>  
        <h4> Company Details </h4>

        <form method="POST" action="{{url_for('index')}}">

            {{ form.csrf_token }}

            {{ form.yearsOfExp.label }} {{ form.yearsOfExp }}       

            <input type="submit" value="Submit">
        </form>

        <hr>
        <h4> Employee Form </h4>

        <form method="POST" action="{{url_for('index')}}" >

            {{ form1.csrf_token }}

            {{ form1.fullName.label }} {{ form1.fullName }}

            {{ form1.dept.label }} {{ form1.dept }}

            <input type="submit" value="Submit">
        </form>
    </body>
</html>

显示数据.html

<html>
    <head> 
    </head> 
    <body>
        {% if form1 %}
        <h2> Employee Details </h2>
            {{ form1.fullName.data }}
            {{ form1.dept.data }}
        {% endif %}
        {% if form %}
            <h2> Company Details </h2>
                {{ form.yearsOfExp.data }}      
        {% endif %}     
    </body>
</html>
于 2019-02-14T10:20:27.770 回答