sujata sujata - 1 month ago 8
Python Question

Form validation in another route Flask

I have a flask wtform. I am able to validate the form in a route where it is instantiated. But I want to validate it from another route. Without using session variable, Is there any other way by which I can access the form object from the other route?

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>


The above code works completely fine. But I want to do something like the below:

@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")


I am getting the following error upon trying the above code.

NameError: global name 'form' is not defined

Answer

You have to call the Fruit class with request.form

@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")