django :: 如何在表单中样式化 CheckboxSelectMultiple?

10 投票
1 回答
8872 浏览
提问于 2025-04-17 23:32

forms.py

class FormEntry(forms.ModelForm):
  class Meta:
    model = Entry
    fields = ['name','price','share']
    widgets = {
      'share':forms.CheckboxSelectMultiple(),
    }

在把它放进模板之后:

<ul id="id_share">
<li><label for="id_share_0"><input id="id_share_0" name="share" type="checkbox" value="2"> lily</label></li>
<li><label for="id_share_1"><input id="id_share_1" name="share" type="checkbox" value="1"> rabbit</label></li>
</ul>

现在我想去掉ul和li标签,同时,我想用bootstrap3的按钮组来美化它,像这样:

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary">
    <input id="id_share_0" name="share" type="checkbox" value="2"> aaa
  </label>
  <label class="btn btn-primary">
    <input id="id_share_1" name="share" type="checkbox" value="1"> bbb
  </label>
</div>

如果有人能给我一个通用的解决方案,那就太好了,而不是从views.py传递具体的值。我的想法是写一个小部件,但我就是搞不懂该怎么做。

1 个回答

19

从Django 1.6开始,你可以使用循环来处理一些事情:

<div class="btn-group" data-toggle="buttons"> 
{% for checkbox in myform.shares %}
    <label class="btn btn-primary">
    {{ checkbox.tag }} {{ checkbox.choice_label }}
    </label>
{% endfor %}
</div>

撰写回答