Очень тревиальная задача:
Сделать группировку для позиций выбора в поле формы.
Не нашел этого в документации, но нашел, что есть такая возможность в class ChoiceWidget(Widget) файла /django/forms/widgets.py
Вот он:
def options(self, name, value, attrs=None):
"""Yield a flat list of options for this widgets."""
for group in self.optgroups(name, value, attrs):
yield from group[1]
def optgroups(self, name, value, attrs=None):
"""Return a list of optgroups for this widget."""
groups = []
has_selected = False
for index, (option_value, option_label) in enumerate(self.choices):
if option_value is None:
option_value = ''
subgroup = []
if isinstance(option_label, (list, tuple)):
group_name = option_value
subindex = 0
choices = option_label
else:
group_name = None
subindex = None
choices = [(option_value, option_label)]
groups.append((group_name, subgroup, index))
for subvalue, sublabel in choices:
selected = (
str(subvalue) in value and
(not has_selected or self.allow_multiple_selected)
)
has_selected |= selected
subgroup.append(self.create_option(
name, subvalue, sublabel, selected, index,
subindex=subindex, attrs=attrs,
))
if subindex is not None:
subindex += 1
return groups
Не могу разобраться, как передать в виджет группы, но формат, похоже такой: [(group1, ) (chois1,) (0,)]
В шаблоне виджета Select такой код:
<select name="{{ widget.name }}"{% include
"django/forms/widgets/attrs.html" %}>{% for group_name, group_choices,
group_index in widget.optgroups %}{% if group_name %} <optgroup
label="{{ group_name }}">{% endif %}{% for option in group_choices %}
{% include option.template_name with widget=option %}{% endfor %}{% if
group_name %} </optgroup>{% endif %}{% endfor %} </select>
Updated 28 Feb. 2021, 19:04 by Dima_Skokov.