Form.attrsを使用する可能性が最も高いのはindex
です。メソッドのparamにいくつかの条件付きガードを追加しました。彼らがGET
またはPOST
を使用している場合、あなたは異なることをしたいと思います。これを行うには他の方法もありますが、あまりにも多くを一度に変更したくはありませんでした。しかし、あなたはそれをこのように明確に考えなければなりません。私が最初のリクエストをしたためにフォームデータがない場合は、GET
を使用します。テンプレートにフォームをレンダリングしたら、POST
(テンプレートの上部に表示されているように)を送信します。だから私は最初に扱った2つのケースが必要です。
フォームがレンダリングされて返されると、私はデータを持つか、データを持たないでしょう。したがって、データの処理はコントローラの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)
大変感謝しています。これはよく助けになります! –
nps。 @ダビデズムは正しい、そして超スマートです。私はちょうどあなたが求めていたよりも多くの問題を抱えていることを知っていて、何らかの文脈を提供したいと思っていました。がんばろう。 –
あなたは正しいです、私はちょうど初心者です、あなたの助けに感謝! –