问题
I'm using a choiceField with the CheckboxSelectMultiple widget. Is it possible to render all checkboxes as checked by default? Thanks!
回答1:
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)
)
回答2:
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":""})
)
来源:https://stackoverflow.com/questions/2229029/django-choicefield-with-checkboxselectmultiple-all-selected-by-default