【问题标题】:Key error: html 5 form submission using pyramid关键错误:html 5表单提交使用金字塔
【发布时间】:2013-10-15 18:35:12
【问题描述】:

我有一个非常简单的金字塔/pylons web 应用程序,只有一个页面(主页)在 home.pt 模板上详细说明,如下所示:

 <form action="/" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<fieldset>
<div>
<input type="radio" name="myradio" value="left" id="choice1"/>
<label for="choice1">Choice1</label>
<input type="radio" name="myradio" value="right" id="choice2"/>
<label for="choice2">Choice2</label></div>
<p>Form Controls</p>
<input type="submit" name='form.submitted' value="Submit"/>
<input type="reset" value="Reset"/>
</fieldset>
</form>

这是与之关联的视图配置:

@view_config(route_name='home', renderer='templates/home.pt')
def home(request):
    choices=random.sample(ranges.items(),2)
    choice1=choices[0]
    choice2=choices[1]
    output=request.GET["myradio"]
    return {'choice1':choice1,'choice2':choice2, 'output':output, "myradio":myradio}

这给了我一个简单的KeyError: 'myradio'

编辑:如果我需要更多详细信息,请随时询问。

【问题讨论】:

  • 阅读 http 表单提交。 w3schools.com/html/html_forms.asp 并且您要查找的值将在您的视图函数中 request.POST 的字典中。
  • 但它会是 request.POST[?]。会是 request.POST[choice1,choice2] 吗?它会输出一个布尔值、一个变量、一个字符串吗?

标签: python html unicode pyramid


【解决方案1】:

你应该可以只做request.POST.get('myradio'),这将根据选择返回“左”或“右”。

【讨论】:

  • 当我这样做时,我得到 TypeError: 'instancemethod' object has no attribute 'getitem'。当我删除 .get(请参阅上面的更新代码)时,我得到 KeyError: "No key 'myradio': Not a form request"。
【解决方案2】:

好的,这就是我修复它的方法。

代替

output=request.GET["myradio"]

我现在有

post_data=request.POST
output=post_data.get('myradio')

当然,我还必须将表单更改为获取表单(在上面的问题中更新)

如果我选择左按钮并提交,则输出“左”,如果选择右按钮并提交,则输出“右”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    • 2013-01-27
    • 2011-08-11
    • 1970-01-01
    • 2013-01-04
    • 2021-09-17
    相关资源
    最近更新 更多