Pyramid应用:如何将值传递给我的request.route_url?
我在我的 views.py 文件中设置了主页的视图配置:
@view_config(route_name='home_page', renderer='templates/edit.pt')
def home_page(request):
if 'form.submitted' in request.params:
name= request.params['name']
body = request.params['body']
page=Page(name,body)
DBSession.add(page)
return HTTPFound(location=request.route_url('view_page',pagename=name))
return {}
另外,这里是 edit.pt 模板中的表单:
<form action="/view_page" method="post">
<div>
<input type="text" name="name"/>
</div>
<div>
<input type="text" name="body"/>
</div>
<label for="stl">Stl</label>
<input name="stl" type="file" value="" />
<input type="submit" name='form.submitted' value="Save"/>
</form>
在我的 init.py 文件中,我有:
config.add_route('home_page', '/')
config.add_route('view_page', '/{pagename}')
现在,当我提交表单时,它只是试图跳转到 localhost:6543/view_page。这会返回一个 404 错误,因为没有名为 view_page 的资源或路由。相反,我希望它跳转到 localhost:6543/(我刚创建的页面的名称,也就是表单中的第一个输入框)。我该怎么做呢?
补充:我担心可能有其他地方指示它跳转到 view_page,因为我甚至尝试将其更改为:
return HTTPFound(location=request.route_url('front_page',pagename=name))
但它仍然跳转到 /view_page。没有名为 front_page 的路由,所以我至少认为它应该报错。
另外,如果你能告诉我你在哪里找到这些信息,我会非常感激。我一直在查看 http://docs.pylonsproject.org/projects/pyramid/en/1.4-branch/api/request.html?highlight=request.route_url#pyramid.request.Request.route_url,但似乎找不到有用的信息。
补充:我应该使用资产规范而不是路径名称吗?所以:
return HTTPFound(Location=request.route_url('tutorial:templates/view.pt','/{pagename}'))
另外,我正在阅读一篇文章,似乎对语法很有帮助:http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/urldispatch.html#urldispatch-chapter
3 个回答
我首先猜测是因为用的是location
而不是Location
,这个是传给HTTPFound
的参数。
根据你提供的链接,应该是这样的
return HTTPFound(location=request.route_url('view_page',pagename=name))
当你添加了这个路由之后
config.add_route('view_page', '/{pagename}')
并且在之前设置了变量名
name= request.params['name']
我觉得你的表单应该提交到“/”,也就是:
<!-- where your home_page route is waiting for the POST -->
<form action="/" method="post">
根据之前的回答,现在看起来是正确的:
return HTTPFound(location=request.route_url('view_page', pagename=name))