django choiceField with CheckboxSelectMultiple: all selected by default?

佐手、 提交于 2020-01-13 07:52:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!