如何在提交后从WTForms表单中获取数据?我想在表单中输入电子邮件。
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>
答案 0 :(得分:2)
使用Form.attrs进行操作的最可能的地方是index
函数。我在方法参数上添加了一些条件保护。如果他们使用GET
或POST
,您也希望执行不同的操作。还有其他方法可以做到这一切,但我不想立刻改变太多。但是你应该这样清楚地思考它。如果我没有表单数据,因为我刚刚提出了初始请求,那么我将使用GET
。在模板中呈现表单后,我将发送POST
(您可以在模板顶部看到)。所以我需要先处理这两个案件。
然后,一旦表单被渲染并返回,我将有数据或没有数据。因此,处理数据将在控制器的POST
分支中发生。
@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)
为了提供帮助,我在一些工作代码中添加了一个简单的示例。根据您的代码和我的演练,您应该能够遵循它。
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)
答案 1 :(得分:1)