Katharine Osborne
Katharine Osborne

Reputation: 7031

Pre-selecting all the checkboxes when using django.forms.ModelMultipleChoiceField

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"

Upvotes: 4

Views: 1282

Answers (1)

Siegmeyer
Siegmeyer

Reputation: 4512

As was pointed out here, you can just set initial to all values:

# Let's assume this is your choice set
CHOICES = (
    ('a', 'A'),
    ('b', 'B'),
    ('c', 'C')
)

field = forms.MultipleChoiceField(
    ...
    initial=[c[0] for c in CHOICES]
    ...
)

Queryset

Let's assume you want to display Users. Just use:

...
queryset=User.objects.all(),
initial=[u for u in User.objects.all()])
...

It will look like (tried it myself):

enter image description here

Upvotes: 3

Related Questions