0

I am trying to create a MultipleChoiceField form field that contains dynamic choices. I would like to preselect a (dynamic) set of these while the rest should remain unchecked. Is there some way to do this?

widget=forms.CheckboxSelectMultiple(attrs={'checked': 'checked'})

Will cause all choices to be checked, however i only need some to be checked.

Help would be greatly appreciated

Martin
  • 85
  • 1
  • 2
  • 7
  • possible duplicate of [Setting the selected value on a Django forms.ChoiceField](http://stackoverflow.com/questions/657607/setting-the-selected-value-on-a-django-forms-choicefield) – ruddra Mar 31 '15 at 11:32

1 Answers1

0

You have to these choices as the field's initial. For example:

    my_field = forms.MultipleChoiceField(
         widget=forms.CheckboxSelectMultiple(),
         choices=(('foo', 'Foo text'), ('bar', 'Bar text'), ('baz', 'Baz text')),
         initial=('foo', 'bar'))
    )

If you want these values to be dynamic, you must change the initial parameter for your field at any step before rendering the form. This can be achieved like this:

    my_dynamic_initials = ('foo', 'bar')
    my_form.fields['my_field'].initial = my_dynamic_initials
gseva
  • 373
  • 4
  • 10
  • Neither of these worked for me. I pasted your code exactly into my project and none of the choices were selected. Not when I hard coded the options into the form definition and not when I added them dynamically via __init__. – Lehrian Dec 03 '19 at 02:29
  • 1
    Apparently you need to use my_form.initial['my_field'] = my_dynamic_initials NOT my_form.fields['my_field'] = my_dynamic_initials. I still never got the passing of the initial=('foo','bar') as key word arguments working. – Lehrian Dec 03 '19 at 02:37