SelectMultiple 小部件中的默认选定选项

Default selected options in SelectMultiple widget

我将几个 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', <b>value=['1', '3']</b>, choices=CHOICES)

在源代码中我们看到 render_options is implemented as [GitHub]:

    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(<b>self.render_option(selected_choices, option_value, option_label)</b>)
        return '\n'.join(output)

并在 render_option method [GitHub] 中:

    def render_option(self, selected_choices, option_value, option_label):
        if option_value is None:
            option_value = ''
        option_value = force_text(option_value)
        if <b>option_value in selected_choices</b>:
            <b>selected_html = mark_safe(' selected="selected"')</b>
            if not self.allow_multiple_selected:
                # Only allow for a single selection.
                selected_choices.remove(option_value)
        else:
            selected_html = ''
        return format_html('<option value="{}"{}>{}</option>',
                           option_value,
                           selected_html,
                           force_text(option_label))

因此它会检查该值是否在您传递的值列表中。