默认选择 ManyToManyField 中的所有选项 [英] Select all choices in a ManyToManyField by default

查看:24
本文介绍了默认选择 ManyToManyField 中的所有选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在默认情况下选择由 Django 中的 ManyToManyField 生成的多个选择中的所有选项?

Is it possible somehow by default to choose all the choices within a select multiple generated by ManyToManyField in Django?

添加的所有新项目都应该在视图中预先选择所有选项(在添加 AnotherEntity 的新项目时也是如此).

All new items that are added should have all choices selected upfront in the view (also when adding new items of AnotherEntity).

class AnotherEntity(models.Model):
    name = models.CharField()

class SomeEntity(models.Model): 
    anotherEntity = models.ManyToManyField(AnotherEntity)

在上面的示例中,我希望在所有新项目中选择 anotherEntity 中的所有选项.

In the example above i wish to have all choices in anotherEntity selected in all new items.

推荐答案

只需继承 SelectMultiple 小部件并覆盖: 1)render_option 渲染所有选定的;2) render_options 控制我们渲染所有选择的位置和默认位置.

Just inherit SelectMultiple widget and override: 1)render_option to render all selected; 2) render_options control where we have render all selected and where as default.

class CustomSelectMultiple(SelectMultiple):
    def render_options(self, choices, selected_choices):
        if not selected_choices:
            # there is CreatView and we have no selected choices - render all selected
            render_option = self.render_option
        else:
            # there is UpdateView and we have selected choices - render as default
            render_option = super(CustomSelectMultiple, self).render_option

        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="{0}">', force_text(option_value)))
                for option in option_label:
                    output.append(render_option(selected_choices, *option))
                output.append('</optgroup>')
            else:

                output.append(render_option(selected_choices, option_value, option_label))
        return '
'.join(output)

    def render_option(self, selected_choices, option_value, option_label):
        option_value = force_text(option_value)
        selected_html = mark_safe(' selected="selected"')

        return format_html('<option value="{0}"{1}>{2}</option>',
                           option_value,
                           selected_html,
                           force_text(option_label))

然后在表单中将小部件设置为您的字段:

Then set widget to your field in form:

class SomeEntityModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(SomeEntityModelForm, self).__init__(*args, **kwargs)

        self.base_fields['anotherEntity'].widget = CustomSelectMultiple()

    class Meta:
        model = SomeEntity

这篇关于默认选择 ManyToManyField 中的所有选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆