我正在将几个forms.SelectMultiple
小部件作为渲染它们的快捷方式传递给视图。有什么方法可以通过默认情况下需要检查哪些选项?源代码似乎不允许这样做:
class SelectMultiple(Select):
allow_multiple_selected = True
def render(self, name, value, attrs=None, choices=()):
if value is None:
value = []
final_attrs = self.build_attrs(attrs, name=name)
output = [format_html('<select multiple="multiple"{}>', flatatt(final_attrs))]
options = self.render_options(choices, value)
if options:
output.append(options)
output.append('</select>')
return mark_safe('\n'.join(output))
def value_from_datadict(self, data, files, name):
if isinstance(data, (MultiValueDict, MergeDict)):
return data.getlist(name)
return data.get(name, None)
再次,让我重复一遍,我仅使用小部件。它没有绑定到任何表单字段,所以我不能使用initial
。
所选元素的列表在value
中。因此,您可以使用以下方法制作小部件:
CHOICES = [
('1', 'red'),
('2', 'green'),
('3', 'blue'),
]
widget=forms.SelectMultiple()
widget.render('item-name', value=['1', '3'], choices=CHOICES)
在源代码中,我们看到render_options
is implemented as [GitHub]:
render_options
和 def render_options(self, choices, selected_choices):
# Normalize to strings.
selected_choices = set(force_text(v) for v in selected_choices)
output = []
for option_value, option_label in chain(self.choices, choices):
if isinstance(option_label, (list, tuple)):
output.append(format_html('<optgroup label="{}">', force_text(option_value)))
for option in option_label:
output.append(self.render_option(selected_choices, *option))
output.append('</optgroup>')
else:
output.append(self.render_option(selected_choices, option_value, option_label))
return '\n'.join(output)
中的:
render_option
method [GitHub]
因此它检查该值是否在您传递的值列表中。