Python 从WTForms表单获取数据
提交后如何从WTForms表单获取数据?我想在表格中输入电子邮件Python 从WTForms表单获取数据,python,flask,wtforms,Python,Flask,Wtforms,提交后如何从WTForms表单获取数据?我想在表格中输入电子邮件 class ApplicationForm(Form): email = StringField() @app.route('/', methods=['GET', 'POST']) def index(): form = ApplicationForm() if form.validate_on_submit(): return redirect('index') retur
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.csrf_token}
{{form.email}
每个字段都有一个包含已处理数据的属性
the_email = form.email.data
处理表单数据在中有说明。处理表单的最可能位置是
index
函数。我在方法param上添加了一些条件保护。如果他们同时使用GET
或POST
,那么您需要做不同的事情。还有其他方法可以做到这一切,但我不想一下子改变太多。但你应该这样想清楚。如果我没有表单数据,因为我刚刚提出了初始请求,我将使用GET
。在模板中呈现表单后,我将发送一个帖子
(如模板顶部所示)。所以我需要先处理这两个案子
然后,一旦表单呈现并返回,我将有数据或没有数据。因此,数据处理将在控制器的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)