Django如何将ModelForm字段渲染为多选

时间:2013-10-29 20:11:57

标签: django django-forms

我有一个这样的模型表单:

from django.forms import widgets

class AdvancedSearchForm(forms.ModelForm):

    class Meta:
        model= UserProfile
        fields = ( 'name', 'location', 'options')

其中'options'是元组列表,并在模板中自动呈现为下拉菜单。但是我希望用户能够在搜索表单中选择多个选项。

我知道我需要在查看docs时向窗体类添加一个窗口小部件,在我看来它需要类似于这样的类:

widgets = {
    'options':  ModelChoiceField(**kwargs)
} 

但是我收到此错误

name 'MultipleChoiceField' is not defined

所以最后无法弄清楚如何实现这一点。非常感谢你的帮助。

1 个答案:

答案 0 :(得分:2)

ModelChoiceField不是小工具,而是form field,但要使用multiple version,您需要覆盖字段:

class AdvancedSearchForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(AdvancedSearchForm, self).__init__(*args, **kwargs)
        self.fields['options'].empty_label = None

    class Meta:
        model= UserProfile
        fields = ( 'name', 'location', 'options')

然后将小部件覆盖为复选框,使用CheckboxSelectMultiple

widgets = {
    'options':  forms.CheckboxSelectMultiple()
} 
相关问题