简体   繁体   English

Django:在表单属性MultipleChoiceField上设置选择

[英]Django: Set choices on form attribute MultipleChoiceField

I have the following django form: 我有以下django形式:

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 . 现在, 我想从views.py指定此MultipleChoiceField的选择。 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. 与ChoiceField一样,接受一个额外的必需参数choices。

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: 在您的views.py中,您必须设置:

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. 这对我有用,我不确定您是否可以避免在Forms.py中不设置choices 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. 我认为您无论如何都需要将其放入forms.py中,如果这是MultipleChoiceField的必需参数,否则您的表单可能无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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