flask中如何实现支持template传参的redirect.

2013-01-19 23:07:07 +08:00
 ry_wang
比如当前有两个页面:
一个创建用户的页面, http://localhost/user/create,对应user_create方法,对应user_create.html模板.
一个用户列表显示页面, http://localhost/user/show,对应user_show方法,对应user_show.html模板.

用户创建成功后通过redirect将页面重定向到/user/show这个页面展示所有的用户列表.现在我在页面中显示一个user create successful或fail的message. 但redirect不支持类似render_template这种的传参功能.

不知各位有啥好的解决办法呢?谢谢.
下面为这个问题的代码.那个message传不进去参数...

@app.route('/operate/create', methods=("GET", "POST"))
def user_create():
form = UserCreateForm()
if request.method == 'GET':
return render_template('user/user_create.html', form=form)
elif request.method == 'POST':
user = User(0, form.user.data, form.password.data)
db.session.add(user)
db.session.commit()
return redirect(url_for('user_show', status='success', message='User create successful.'))

@app.route('/user/show')
def user_show():
if request.method == 'GET':
users = User.query.filter_by(type=0).order_by(desc(User.id)).all()
return render_template('user_show.html', users=users)
12347 次点击
所在节点    Flask
3 条回复
lix
2013-01-19 23:15:58 +08:00
用flash
linnchord
2013-01-19 23:16:49 +08:00
这个……最基础的问题,看清楚文档先……

如果你确实要传递url参数,请定义好方法参数

@app.route('/user/show/<message>')
def user_show(message):

然后才能
return redirect(url_for('user_show', message='User create successful.'))

不过看你上面描述,你只是要显示一个消息,那可以用内置的flash方法

flask中文文档
http://docs.torriacg.org/docs/flask/quickstart.html

哪怕你只看快速入门也可以解答上面问题了
ry_wang
2013-01-19 23:46:33 +08:00
呃,忘掉这块了,谢谢二位..

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/58136

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX