【问题标题】:Get labels from check boxes in form从表单中的复选框获取标签
【发布时间】:2014-03-07 08:44:06
【问题描述】:

我有一个包含一些字段的表单:一个文本区域、一个文本框和随机数量的复选框,具体取决于产品。我想知道如何获取选中的复选框的标签。

这是我的表格:

<form class="form-inline">
<strong><h3>Revise este produto</h3></strong><br>

{% for tag in tags %}
<label class="checkbox">
<input type="checkbox" value=""> #Ótimo
</label>
{% endfor %}

<br/>
<p>&nbsp;</p>
<label>Envie outras hashtags</label> <br/>
<input type="text" class="span3" placeholder="exemplo1, exemplo2">
<br />
<p>&nbsp;</p>
<label>Deixe sua opinião (opcional)</label> <br/>
<textarea name="Text1" cols="80" class="span3" rows="5" placeholder="Digite sua opinião aqui"></textarea>
<br/>
<p>&nbsp;</p>
<button class="btn btn-primary" type="submit"><h4>Pronto!</h4></button>
</form>

【问题讨论】:

    标签: python html django django-forms django-templates


    【解决方案1】:

    在models.py中:

    class Tag:
        published = BooleanField()
        (...)
    

    在模板中:

    {% for tag in tags %}
    <label class="checkbox">
    <input type="checkbox" name="tag[]" value="" {% if tag.published %}checked{% endif %}> #Ótimo
    </label>
    {% endfor %}
    

    【讨论】:

      【解决方案2】:
      • 假设您将表单作为 POST 发送,则 选中的复选框位于request.POST.getlist('tag')

        请注意,在 POST 中只发送选中的复选框,但列表 包含所有选中框的值元素。

      例如:

      <input type="checkbox" name="tag[]" value="1" />
      <input type="checkbox" name="tag[]" value="2" />
      <input type="checkbox" name="tag[]" value="3" />
      <input type="checkbox" name="tag[]" value="4" />
      

      说如果检查了 1,4,

      check_values = request.POST.getlist('checks')
      

      check_values 将包含 [1,4](被检查的那些值)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-25
        • 1970-01-01
        • 2014-05-04
        • 1970-01-01
        • 2014-04-05
        相关资源
        最近更新 更多