Flask WTF – Forms always redirect to root

1.5k Views Asked by At

I have created a simple Flask WTF form

class SequenceForm(Form):
    sequence = StringField('Please enter a sequence in FASTA format', validators=[Required()])
    submit = SubmitField('Submit')

and I have set up a route to make it appear on a page

@main.route('/bioinformatics')
def bioinformatics():
    form = SequenceForm()
    return render_template('bioinformatics.html', form=form)

It all works great (so far). When I point my browser to foo/bioinformatics, I see a page with a SequenceForm rendered. However, when I hit the Submit button, I am always taken back to the root page defined by @main.route('/').

How can I make the Submit button take me somewhere else? I would like to use validate_on_submit() and do stuff with the data entered in the form.

Thanks!

/Michael Knudsen

UPDATE (Code from bioinformatics.html)

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}Bioinformatics{% endblock %}

{% block page_content %}

<div class="page-header">
    <h1>Hello, Bioinformatics!</h1>
</div>

{{ wtf.quick_form(form) }}

{% endblock %}
2

There are 2 best solutions below

1
On BEST ANSWER

You need to specify an action in the form in your html.

<form action="/url_which_handles_form_data" method="Post">
   your code
</form>

make sure to give the correct path if you are using blueprints

Edit:

From https://github.com/mbr/flask-bootstrap/blob/master/flask_bootstrap/templates/bootstrap/wtf.html I found this part.

{% macro quick_form(form,
                action="",
                method="post",
                extra_classes=None,
                role="form",
                form_type="basic",
                horizontal_columns=('lg', 2, 10),
                enctype=None,
                button_map={},
                id="") %}

So you can probably call

{{ wtf.quick_form(form, action="/fancy_url") }}

or

{{ wtf.quick_form(form, action=url_for("blueprint_name.fancy_url")) }}

Depending on where the view is located.

0
On

Thanks to Tim Rijavec and Zyber. I used a combination of your suggestions to come up with the following solution.

I added GET and POST to methods for the route

@main.route('/bioinformatics', methods=['GET', 'POST'])
def bioinformatics():
    form = SequenceForm()
    return render_template('bioinformatics.html', form=form)

and then I wrapped the wtf.quick_form call inside tags.

<form action="{{ url_for('main.bioinformatics') }}" method="POST">
    {{ wtf.quick_form(form) }}
</form> 

Now everything works beautifully. Thanks!