【问题标题】:Passing a Tuple of Values through a Checkbox通过复选框传递值元组
【发布时间】:2015-04-06 20:04:13
【问题描述】:

我有一个有组织的项目列表,用户可以使用复选框从中选择。我正在尝试为每个选中的复选框传递一组值,以便我可以获得有关项目本身和项目所属组的信息。我尝试过使用隐藏字段,但无论是否选中了相应的复选框,似乎都在传递隐藏字段值。

如果选中复选框,我需要引用 ID 和父软件。我可以为每个选中的复选框传递一个 (citation.id, sw) 元组,并且由于可以选中多个复选框,因此将所有这些作为元组列表一起传递?比如:[(citation1.id, sw1), (citation2.id, sw2), ] ?在我看来,我需要这些信息。

感谢您的帮助!

select_citations.html

{% for sw in software %}
    {{sw}}
    {% for citation in all_citations %}
        <input type="checkbox" name="myselection[]" value="{{citation.id}}">
        <input type="hidden" name="myselection[]" value="{{sw}}">
    {% endfor %}
{% endfor %}

【问题讨论】:

  • 我也试过这个,但它似乎并没有真正添加/连接我的值:&lt;input type="checkbox" name="myselection[]" value="{{ citation|add:sw }}"&gt;,然后,在我看来:mycitations = request.GET.getlist('myselection[]')

标签: python html django checkbox django-templates


【解决方案1】:

将两个模型的 ID 组合为复选框的单个值:

{% for sw in software %}
  {{sw}}
  {% for citation in all_citations %}
    <input type="checkbox" name="selection" value="{{citation.id}}-{{sw.id}}">
  {% endfor %}
{% endfor %}

然后在视图中解构这个值:

ids = [value.split('-') for value in request.POST.getlist('selection')]

【讨论】:

  • 这正是我需要的@catavaran,但它不起作用......价值观没有通过。即使我不拆分值,列表仍然是空的。还有其他想法吗?
  • 您是否使用“POST”方法发送表单?复选框输入的名称是否与getlist()函数中的名称相同?
  • 我的愚蠢命名错误,对此感到抱歉。非常感谢@catavaran-它有效!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-31
  • 2015-07-04
  • 2010-11-07
  • 1970-01-01
  • 2016-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多