george
george

Reputation: 79

Submit form with flask wtforms with GET method

I have 2 routes :

@app.route('/activity', methods=["GET"])
def addactivity():
    return render_template('activity.html')

In acitvity.html I have a form with some fields and I want to submit this form to another route :

@app.route('/students', methods=["GET"])
def addstudents():
    return render_template('students.html')

So when I submit the form in acitvity.html I will be redirected to

/students?field1=value1&field2=value2 etc...

For activity form i am using wtforms with validators: DataRequired() or InputRequired()

The problem is that when i am using form.validate() in addstudents route even if form is validated or not it will redirect me to students.html route.I want in case the form is not validated to display the errors in activity.html.How is that possible?

I am new to flask and maybe my whole code is wrong, but the concept is that if the activity form is validated i will be redirected to the students route, if not errors will be displayed in activity route.. Furthermore i need to submit the the form in students route with the args of the previous form.

Upvotes: 4

Views: 3019

Answers (1)

Robert White
Robert White

Reputation: 81

You need to pass request.args when you initialize your form, e.g.

@app.route('/students')
def addstudents():
    form = Form(request.args)

    if form.validate():
        return render_template('students.html')

    # Redirect to addactivity if form is invalid
    return redirect(url_for('addactivity'))

You will need to import the request object from flask.

Source: https://github.com/lepture/flask-wtf/issues/291

To redirect to addstudents when the form is submitted, add the attribute action="{{ url_for('addstudents') }}" to the <form> tag in activity.html.

Upvotes: 8

Related Questions