在另一条路线Flask

时间:2016-09-29 08:45:22

标签: python flask flask-wtforms

我有一个烧瓶重量。我能够在实例化的路径中验证表单。但我想从另一条路线验证它。不使用会话变量,有没有其他方法可以从其他路径访问表单对象?

form_class.py

class Fruit ( Form):
    Fruit = SelectField ( choices = [ ( 0,"Select Fruit"), ( 1,'Apple'), (2,'Grape'), (3,'Orange') ], coerce = int, id="Fruit", validators = [Required()])  

views.py

@app.route('/fruit',  methods = ['GET', 'POST'])
def fruit():
    form = Fruit()
    if form.validate_on_submit():
       return render_template("output.html")
    return render_template("name.html", form = form)

name.html

<form action="" method="POST">
      {{ form.hidden_tag() }}
      {{form.Fruit}}
      {{form.Fruit.errors}}
      <input type = "submit">
</form>

以上代码完全正常。但我想做类似下面的事情:

@app.route('/fruit')
def fruit():
    form = Fruit()
    '''if form.validate_on_submit():
       return render_template("output.html")'''
    return render_template("name.html", form = form)

@app.route('/fruit_submit', methods = ['GET', 'POST'])
def fruit_submit():
    print request.form
    if form.validate_on_submit():
       return render_template("output.html")

尝试上述代码时出现以下错误。

NameError: global name 'form' is not defined

1 个答案:

答案 0 :(得分:0)

您必须使用request.form

调用Fruit类
@app.route('/fruit_submit', methods = ['GET', 'POST'])
def fruit_submit():
    print Fruit(request.form)
    if Fruit(request.form).validate_on_submit():
       return render_template("output.html")