Django: Set choices on form attribute MultipleChoi

2019-05-21 08:46发布

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!

2条回答
迷人小祖宗
2楼-- · 2019-05-21 09:14

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)
查看更多
男人必须洒脱
3楼-- · 2019-05-21 09:25

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 choicesin 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.

查看更多
登录 后发表回答