Form.attrs로 작업 할 가능성이 가장 높은 곳은 index
입니다. 메소드 param에 몇 가지 조건 가드를 추가했습니다. 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)
와우 덕분에, 나는 이처럼 자세히 설명 할 것을 기대하지 않았습니다. 이것은 잘 도움이 많이! –
nps. @ 데이비드 즘은 정확하고 슈퍼 영리합니다. 방금 당신이 물어 보는 것보다 더 많은 문제를 겪고 있다는 것을 느꼈고, 약간의 맥락을 제공하고 싶었습니다. 행운을 빕니다. –
당신이 옳았어요, 난 그냥 초보자예요, 당신 덕분에! –