首页 > 解决方案 > django 表单:CheckboxSelectMultiple 的 id_for_label 不起作用

问题描述

我想自定义我的标签样式,所以我在我的 html 模板中使用 for 循环覆盖所有选项中的 {{ form }}。但是我发现在使用 for 循环后,我丢失了每个选项的输入标签“for”属性和“id”。 旧代码: html模板:

{% block form %}
<button class="checker">Uncheck all</button>  <button class="allChecker">Check all</button>
  <form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form }}
    <br/>
    <input type="submit" value="Submit">
  </form>
{% endblock %}

我的表格:

class RerunForm(forms.Form):
    items = ItemStatus(
        queryset=models.Container.objects.none(),
        widget=forms.CheckboxSelectMultiple(attrs=dict(checked='')),
        help_text="Select requirements/objectives that you want to rerun.",
    )

    def __init__(self, rerunqueryset, *args, **kwargs):
        super(RerunForm, self).__init__(*args, **kwargs)
        self.fields['items'].queryset = rerunqueryset

class ItemStatus(models.ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        if '_' not in obj.name:
            return "{} ({})".format(obj.name.replace('-r1', '').replace('-s1', ''), obj.state)
        else:
            return ". . . {} ({})".format(obj.name.replace('-r1', ''), obj.state)

新代码:html模板:

{% block form %}
<button class="checker">Uncheck all</button>  <button class="allChecker">Check all</button>
  <form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <ul id="id_items">
      {% for value, label, item in form.items.field.choices %}
      <li>
        <label for="{{ form.items.id }}">
          <input type="checkbox" value={{ value }} name="items" id="{{ form.items.auto_id }}">
          <span class="listItem-{{item.state}}">{{ label }}</span>
        </label>
      </li>
      {% endfor %}
    </ul>    <br/>
    <input type="submit" value="Submit">
  </form>
{% endblock %}

新形式:

class RerunForm(forms.Form):
    items = ItemStatus(
        queryset=models.Container.objects.none(),
        widget=forms.CheckboxSelectMultiple(attrs=dict(checked='')),
        help_text="Select requirements/objectives that you want to rerun.",
    )

    def __init__(self, rerunqueryset, *args, **kwargs):
        super(RerunForm, self).__init__(*args, **kwargs)
        self.fields['items'].queryset = rerunqueryset

class ItemStatus(models.ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        if '_' not in obj.name:
            return "{} ({})".format(obj.name.replace('-r1', '').replace('-s1', ''), obj.state)
        else:
            return ". . . {} ({})".format(obj.name.replace('-r1', ''), obj.state)

    def _get_choices(self):
        if hasattr(self, '_choices'):
            return self._choices
        return CustomModelChoiceIterator(self)

    choices = property(_get_choices,
                       MultipleChoiceField._set_choices)


class CustomModelChoiceIterator(models.ModelChoiceIterator):
    def choice(self, obj):
        # return super(CustomModelChoiceIterator, self).choice(obj)
        return (self.field.prepare_value(obj),
                self.field.label_from_instance(obj),
                obj)

旧代码<label for='id_items_1'><input ... id='id_items_1>...在我检查时给了我,但新代码只给了我<label><input ...>没有 for 和 id 属性。我尝试添加<label for="{{ form.items.id_for_label }}>html,没有运气。然后<label for="{{ form.items.auto_it }}>给了我<label for="id_items">,但不区分选择。请帮助了解如何添加 'id_items_0'、'id_items_1'、... 作为标签 'for' 并将 'id' 输入到我在 html 中的每个选择中?我还用新代码附上了它现在的样子。 网页并使用新代码检查结果

标签: htmldjangoforms

解决方案


推荐阅读