Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

django

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"
like image 654
Katharine Osborne Avatar asked Oct 24 '25 07:10

Katharine Osborne


1 Answers

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

like image 169
Siegmeyer Avatar answered Oct 25 '25 21:10

Siegmeyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!