Select all choices in a ManyToManyField by default

坚强是说给别人听的谎言 提交于 2019-12-11 04:08:46

问题


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

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)

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


回答1:


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 '\n'.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



回答2:


you can override save methos of model like this:

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

    def save(self, *args, **kwargs):
        choices = AnotherEntity.objects.all()
        for choice in choices:
            self.anotherentity.add(choice)
        super(SomeEntity, self).save(*args, **kwargs)


来源:https://stackoverflow.com/questions/26578266/select-all-choices-in-a-manytomanyfield-by-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!