如何在Google App Engine中重定向并显示错误
我正在做一个Google App Engine的项目,目的是收集用户提交的故事。
这是我在请求处理器的post方法中处理提交错误的方式:
# get the title and content using self.request.get()
errors = []
if not title:
errors.append("Please enter a title.")
if not content:
errors.append("Please enter a story.")
if not errors:
# create the story, save it to the database
# redirect to the story's page
else:
# pass the title and/or content to a template
# pass the error message(s) to a template
# the same template that displays the submission form is used here
问题:因为我的表单是发送到 example.com/createstory.do 的,所以如果出现错误,我最终会在那个地址重新显示表单页面。
我想要的效果:把用户重定向回他们提交表单的页面:example.com/Share,同时显示错误信息,并重新显示用户提交的表单数据。
有什么简单的方法可以做到这一点吗?
我知道我可以让 /Share 同时处理get和post请求,但我希望找到一个即使在那种情况下也能使用的解决方案。
2 个回答
1
其实没有一种“干净”的方法来做到这一点,因为你不能把POST请求重定向到另一个地方,同时让重定向后的请求也变成POST请求。最标准、最简单的方法是让同一个网址在用GET请求时显示表单,而在用POST请求时接收数据。
1
如果你真的需要使用不同的网址,可以把错误信息放在网址的GET变量里,然后重定向到/Share。不过这样做会让你的网址看起来很乱,因为里面会包含所有的错误信息。
另一种选择是重定向回Share,把错误信息存储在cookies或者会话变量里。
最好的办法可能是先在提交表单之前,用Javascript进行客户端的表单验证,这样就能避免大多数情况下出现那个乱糟糟的解决方案。