在Formencode验证失败后,用Querystring参数重新读取塔架形式
-
13-10-2019 - |
题
我的问题可能与此相同,但是建议的答案似乎没有帮助(或者我不正确理解): 塔架构造@Validate Decorator将参数转换为重新渲染动作
我有一个简单的表单,该表单采用必需的querystring(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。
这似乎是如此简单,但是我缺少什么?
解决方案
如果您在newnode中使用ID arg,我的首选是在其相关的createNode函数中使用相同的arg。调整您的帖子URL使用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>
其他提示
当验证失败时 validate
装饰者打电话给你 newnode
修改后 request
对象,但是所有获取/帖子参数必须不更改
def newnode(self, id=None):
c.parent_id = id or request.params.get('parent_id')
return render('newnode.html')
不隶属于 StackOverflow