我正在尝试创建一个由查询集填充的多项选择字段。
我的表格如下所示:
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)
选择显示没有任何问题。
为什么我的查询集没有分配给小部件?
MultipleChoiceField
不接受queryset
参数,但它接受choices
:https://docs.djangoproject.com/en/dev/ref/forms/fields/#multiplechoicefield
ModelMultipleChoiceField 接受查询集。