Get data from WTForms form

12,824

Solution 1

Each field has a data attribute containing the processed data.

the_email = form.email.data

Working with form data is described in the getting started doc.

Solution 2

The most probable place for you to do things with the Form.attrs is in the index function. I have added some conditional guards on the method param. You want to do different things if they are using GET or POST as well. There are other ways to do all of this but I didn't want to change too much at once. But you should think about it clearly this way. If I have no form data because I've just made the initial request, I'm going to be using GET. Once I render the form in the template, I'm going to be sending a POST (as you can see in the top of your template). So I need those two cases dealt with firstly.

Then, once the form is rendered and returned I will have data or no data. So dealing with the data is going to happen in the POST branch of the controller.

@app.route('/index', methods=['GET', 'POST'])
def index():
    errors = '' 

    form = ApplicationForm(request.form)
    if request.method == 'POST':
        if form.is_submitted():
            print "Form successfully submitted"
        if form.validate_on_submit():
            flash('Success!')
            # Here I can assume that I have data and do things with it.
            # I can access each of the form elements as a data attribute on the
            # Form object.
            flash(form.name.data, form.email.data)
            # I could also pass them onto a new route in a call.
            # You probably don't want to redirect to `index` here but to a 
            # new view and display the results of the form filling.
            # If you want to save state, say in a DB, you would probably
            # do that here before moving onto a new view.
            return redirect('index')
        else:  # You only want to print the errors since fail on validate
            print(form.errors)  
            return render_template('index.html',
                                   title='Application Form',
                                   form=form)
    elif request.method == 'GET':
        return render_template('index.html', 
                               title='Application Form',
                                   form=form)

To help, I'm adding a simple example from some of my working code. You should be able to follow it given your code and my walk through.

def create_brochure():
    form = CreateBrochureForm()
    if request.method == 'POST':
        if not form.validate():
            flash('There was a problem with your submission. Check the error message below.')
            return render_template('create-brochure.html', form=form)
        else:
            flash('Succesfully created new brochure: {0}'.format(form.name.data))
            new_brochure = Brochure(form.name.data,
                                    form.sales_tax.data,
                                    True,
                                    datetime.datetime.now(),
                                    datetime.datetime.now())
            db.session.add(new_brochure)
            db.session.commit()
            return redirect('brochures')
    elif request.method == 'GET':
        return render_template('create-brochure.html', form=form)
Share:
12,824

Related videos on Youtube

davidism
Author by

davidism

I'm a core developer on the Pallets open source team, who develop Flask, Werkzeug, Jinja, Click, and more. I also develop WTForms, Flask-WTF, Flask-SQLAlchemy, Flask-Alembic, and contribute to others. Come join us in the sopython chatroom!

Updated on June 04, 2022

Comments

  • davidism
    davidism almost 2 years

    How do I get the data from a WTForms form after submitting it? I want to get the email entered in the form.

    class ApplicationForm(Form):
        email = StringField()
    
    @app.route('/', methods=['GET', 'POST'])
    def index():
        form = ApplicationForm()
    
        if form.validate_on_submit():
            return redirect('index')
    
        return render_template('index.html', form=form)
    
    <form enctype="multipart/form-data" method="post">
        {{ form.csrf_token }}
        {{ form.email }}
        <input type=submit>
    </form>