Get data from WTForms form

放肆的年华 提交于 2019-12-01 05:47:26

问题


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>

回答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.




回答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)


来源:https://stackoverflow.com/questions/40916185/get-data-from-wtforms-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!