Я хочу настроить стиль метки, поэтому я перезаписываю {{form}} в своем html-шаблоне циклом for для всех вариантов. Но я обнаружил, что потерял метку «для» атрибута и «идентификатор» ввода для каждого выбора после использования цикла for. Старые коды: 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? Я также приложил то, на что это похоже теперь с новыми кодами. веб-страницу и проверить результаты с новыми кодами