多选字段在 django 中不显示查询集

问题描述 投票:0回答:1

我正在尝试创建一个由查询集填充的多项选择字段。

我的表格如下所示:

class GroupLocationForm(forms.Form):
    groups_field = forms.MultipleChoiceField(required=False, 
                                    widget=forms.CheckboxSelectMultiple)

    def __init__(self, customer_id, group_id):
        super(GroupLocationForm, self).__init__()
        customer = Customer.objects.get(pk=customer_id)

        self.fields['groups_field'].queryset = Group.objects.filter(location__customer = customer).distinct()

我的表单中没有任何选择。如果我添加:

MY_CHOICES = (
                  (1,'choice 1'),
)

groups_field = forms.MultipleChoiceField(required=False, 
                                    widget=forms.CheckboxSelectMultiple, choices=MY_CHOICES)

选择显示没有任何问题。

为什么我的查询集没有分配给小部件?

django django-forms
1个回答
15
投票

MultipleChoiceField
不接受
queryset
参数,但它接受
choices
https://docs.djangoproject.com/en/dev/ref/forms/fields/#multiplechoicefield

ModelMultipleChoiceField 接受查询集。

© www.soinside.com 2019 - 2024. All rights reserved.