I am passing several forms.SelectMultiple widgets to a view as a shortcut to render them. Is there any way to pass which options need to be checked by default? The source code doesn't seem to allow that:
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)
Again, let me repeat I am only using the widget. It is not bound to any form field, so I can't use initial.
The list of selected elements is in the
value. So you can make a widget with:In the source code we see that the
render_optionsis implemented as [GitHub]:and in the
render_optionmethod [GitHub]:so it checks if the value is in the list of values you passed.