简体   繁体   中英

Django: Set choices on form attribute MultipleChoiceField

I have the following django form:

class SpecifyColumnsForm(forms.Form):
    columns = forms.MultipleChoiceField(required=False,
    widget=forms.CheckboxSelectMultiple)

Now, I want to specify the choices for this MultipleChoiceField from views.py . How can I do that?

I have tried the following, but it did not work:

        columns_form = SpecifyColumnsForm(request.POST)
        columns_form.choices = (('somestuff', 'spam'),
                                ('otherstuff', 'eggs'),
                                ('banana', 'bar'))

Thanks!

The documentation itself states that

class MultipleChoiceField(**kwargs)¶

[...]

Takes one extra required argument, choices, as for ChoiceField.

So all you have to do is

cool_choices = (('somestuff', 'spam'),
                ('otherstuff', 'eggs'),
                ('banana', 'bar'))

class SpecifyColumnsForm(forms.Form):
    columns = forms.MultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple,
        choices=cool_choices)

In your views.py you have to set:

choices = (('somestuff', 'spam'),
           ('otherstuff', 'eggs'),
           ('banana', 'bar'))
form.fields["columns"].choices = choices

This works for me, I'm just not sure if you can avoid to not set choices in forms.py. I think you need anyway to put it in forms.py, if this is a required argument for MultipleChoiceField otherwise your form might not be valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM