问题
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