在FormEncode验证失败后,使用查询字符串参数重新呈现Pylons表单

时间:2011-01-20 02:09:42

标签: python pylons validation formencode

我的问题可能与此相同,但建议的答案似乎没有帮助(或者我没有正确理解):Pylons FormEncode @validate decorator pass parameters into re-render action

我有一个简单的表单,它接受一个必需的查询字符串(id)值,将其用作隐藏表单字段值,并验证发布的数据。控制器如下所示:

class NewNodeForm(formencode.Schema):
  parent_id = formencode.validators.Int(not_empty = True)
  child_name = formencode.validators.String(not_empty = True)

def newnode(self, id):
  c.parent_id = id
  return render('newnode.html')

@validate(schema=NewNodeForm(), form='newnode')
def createnode(self):
  parentId = self.form_result.get('parent_id')
  childName = self.form_result.get('child_name')
  nodeId = save_the_data(parentId, childName)
  return redirect_to(controller = 'node', action = 'view', id = nodeId)

并且表格非常基本:

<form method="post" action="/node/createnode">
  <input type="text" name="child_name">
  <input type="hidden" value="${c.parent_id}" name="parent_id">
  <input name="submit" type="submit" value="Submit">
</form>

如果验证通过,一切正常,但如果失败,则无法调用newnode,因为id未传回。它抛出TypeError: newnode() takes exactly 2 arguments (1 given)。简单地定义为newnode(self, id = None)可以解决问题,但我不能这样做,因为逻辑需要id。

这看起来很简单,但我错过了什么?

2 个答案:

答案 0 :(得分:1)

如果你在newnode中使用id arg,我的偏好是在它的相关createnode函数中使用相同的arg。调整你的帖子网址以使用id,你不需要隐藏parent_id,因为它现在是url的一部分。

<form method="post" action="/node/createnode/${request.urlvars['id']}">
  <input type="text" name="child_name">
  <input name="submit" type="submit" value="Submit">
</form>

答案 1 :(得分:0)

验证失败时,validate装饰器会使用修改后的newnode对象调用request,但不能更改所有GET / POST参数

def newnode(self, id=None):
  c.parent_id = id or request.params.get('parent_id')
  return render('newnode.html')