我想自定义标签样式,因此我使用所有选择的for循环覆盖了html模板中的{{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属性。
我尝试在HTML中添加<label for="{{ form.items.id_for_label }}>
,但不走运。
然后<label for="{{ form.items.auto_it }}>
给了我<label for="id_items">
,但没有将选择从一个区分到另一个。请帮助如何添加“ id_items_0”,“ id_items_1”,...作为标签“ for”,并为我在html中选择的每一个输入“ id”?
我还用新代码附加了现在的外观。
web-page and inspect results with new codes