I want to show pre-selected options to the user (since they are more likely to remove a few items rather than add all the items, which is a hassle).
Is it possible to pre-select all the checkboxes rendered by a ModelMultipleChoiceField?
Would this be done in the model, or the form?
I'd prefer not to use javascript to do it.
I can't find any documentation about pre-selecting for ModelMultipleChoiceField and official documentation is scant: https://docs.djangoproject.com/en/1.11/ref/forms/fields/#modelmultiplechoicefield
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['my_items'] = forms.ModelMultipleChoiceField(
widget=forms.CheckboxSelectMultiple,
queryset=models.MyItem.objects.all(),
initial=self.instance.MyItem.all())
If I add "checked" in the template, I get an error:
{% render_field form.my_items class+="form-control" checked %}
Error:
'render_field' tag requires a form field followed by a list of attributes and values in the form attr="value"