4

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.

5
  • 3
    You have to "POST" forms, unless i missed something Commented Dec 15, 2017 at 19:16
  • You need if request.method == "POST" inside your definition, then put your form validation there. At the end it should be return redirect(url_for('students')) Commented Dec 15, 2017 at 19:20
  • can you add your form.py code? Commented Dec 16, 2017 at 8:41
  • @SuperStew A form can be submitted with POST or GET, depending on the method attribute on the form element. You might use GET for things like search forms, which are not going to cause a change on the server side. See developer.mozilla.org/en-US/docs/Web/HTML/Element/form Commented Dec 16, 2017 at 11:01
  • 1
    Can you add the whole code in add student? Commented Dec 16, 2017 at 11:53

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.