使用单个Serverside变量处理多个复选框

cli*_*ray 3 html python checkbox

我有以下HTML代码:

<form method="post">
              <h5>Sports you play:</h5>
                <input type="checkbox" name="sports_played" value="basketball"> basketball<br>
                <input type="checkbox" name="sports_played" value="football"> football<br>
                <input type="checkbox" name="sports_played" value="baseball"> baseball<br>
                <input type="checkbox" name="sports_played" value="soccer"> tennis<br>
                <input type="checkbox" name="sports_played" value="mma"> MMA<br>
                <input type="checkbox" name="sports_played" value="hockey"> hockey<br>

                <br> 

                    <input class="btn" type="submit">

</form>
Run Code Online (Sandbox Code Playgroud)

然后理想情况下我想拥有以下python服务器端代码:

class MyHandler(ParentHandler):
    def post(self):
        sports_played = self.request.get('sports_played')
        #sports_played is a list or array of all the selected checkboxes that I can iterate through
Run Code Online (Sandbox Code Playgroud)

我尝试通过制作HTML sports_played名称和数组sports_played []来做到这一点,但是没有做任何事情,现在它只是总是返回第一个选定的项目.

这可能吗?真的,我只是不想为每个复选框做一个self.request.get('HTML_item'),我需要改变HTML,我不想改变python.

谢谢!

Dan*_*man 6

答案显示在请求对象webapp2文档中:

self.request.get('sports_played', allow_multiple=True)
Run Code Online (Sandbox Code Playgroud)

或者你可以使用

self.request.POST.getall('sports_played')
Run Code Online (Sandbox Code Playgroud)


Emd*_*won 6

虽然这个答案与这个问题无关,但它可能会帮助所有到处走动的django开发人员。

Django request.POST中是一个QueryDict对象。因此,您可以通过以下方式获取列表中的所有值

request.POST.getlist('sports_played')
Run Code Online (Sandbox Code Playgroud)

注意:这仅适用于 Django


Man*_*ond 5

输入的名称应位于[]末尾,以便将它们作为数组设置到服务器。现在,您的多个复选框将作为许多具有相同名称的变量发送到服务器,因此只能识别一个。它应该看起来像这样:

<form method="post">
              <h5>Sports you play:</h5>
                <input type="checkbox" name="sports_played[]" value="basketball"> basketball<br>
                <input type="checkbox" name="sports_played[]" value="football"> football<br>
                <input type="checkbox" name="sports_played[]" value="baseball"> baseball<br>
                <input type="checkbox" name="sports_played[]" value="soccer"> tennis<br>
                <input type="checkbox" name="sports_played[]" value="mma"> MMA<br>
                <input type="checkbox" name="sports_played[]" value="hockey"> hockey<br>

                <br> 

                    <input class="btn" type="submit">

</form>
Run Code Online (Sandbox Code Playgroud)

现在,如果您选择多个,这些值将作为数组发送。

  • 这是一个 PHP 特定的答案,问题是关于 Python Web 框架的。在 HTML 表单中,您不需要使用“[]”来进行多个输入。只有在 PHP 中,才需要让框架识别多个输入。 (6认同)