Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django choiceField with CheckboxSelectMultiple: all selected by default?

Tags:

django-forms

I'm using a choiceField with the CheckboxSelectMultiple widget. Is it possible to render all checkboxes as checked by default? Thanks!

like image 303
ben Avatar asked Feb 09 '10 12:02

ben


2 Answers

I am doing exactly that on a form using this

class MyForm(forms.Form):
     photo_list = forms.MultipleChoiceField(
         label="Photos", 
         required=False, 
         help_text="Unselect the photos you want to delete", 
         choices=(), 
         widget=forms.CheckboxSelectMultiple(attrs={"checked":""})
     )
like image 72
mcniac Avatar answered Nov 03 '22 17:11

mcniac


Just set the initial values from the field's choices, like this:

MY_CHOICES = (
    ("some", "Some choice"),
    ("another", "Another choice"),
    ("best", "Best choice")
)

...

multiple_choice = forms.MultipleChoiceField(
    label=u"Select multiple", 
    choices=MY_CHOICES, 
    widget=forms.widgets.CheckboxSelectMultiple, 
    initial=(c[0] for c in MY_CHOICES)
)
like image 40
nanook Avatar answered Nov 03 '22 15:11

nanook