tom*_*mmy 9 python redirect flask
我有一份调查表.提交表单后,我想处理保存数据然后重定向到"成功"视图.我现在正在使用以下代码,但它只停留在当前网址上,而我想去/success.我怎样才能做到这一点?
@app.route('/surveytest', methods=['GET', 'POST'])
def surveytest():
if request.method == 'GET':
return render_template('test.html', title='Survey Test', year=datetime.now().year, message='This is the survey page.')
elif request.method == 'POST':
name = request.form['name']
address = request.form['address']
phone = request.form['phone']
email = request.form['email']
company = request.form['company']
return render_template('success.html', name=name, address=address, phone = phone, email = email, company = company)
Run Code Online (Sandbox Code Playgroud)
dav*_*ism 10
您有正确的目标:在处理表单数据后重定向是很好的.而不是render_template再次返回,redirect而是使用.
from flask import redirect, url_for, survey_id
@app.route('/success/<int:result_id>')
def success(result_id):
# replace this with a query from whatever database you're using
result = get_result_from_database(result_id)
# access the result in the tempalte, for example {{ result.name }}
return render_template('success.html', result=result)
@app.route('/survey')
def survey():
if request.method == 'POST':
# replace this with an insert into whatever database you're using
result = store_result_in_database(request.args)
return redirect(url_for('success', result_id=result.id))
# don't need to test request.method == 'GET'
return render_template('survey.html')
Run Code Online (Sandbox Code Playgroud)
重定向将由用户的浏览器处理,并且将加载新URL的新页面,而不是在同一URL上呈现不同的模板.
| 归档时间: |
|
| 查看次数: |
9157 次 |
| 最近记录: |