Django表单字段动态查询集字段

时间:2017-03-06 02:32:26

标签: django django-forms django-views

class EventForm(forms.Form):
    date = forms.DateField(initial=datetime.date.today)
    product = forms.ModelMultipleChoiceField(queryset=Product.objects.all())
    isrecurring = forms.BooleanField(required=False)
    week =  forms.IntegerField(required=False, initial=1)
    days =  forms.ChoiceField(choices = week_days,required=False)

我有一个包含产品字段的表单,该字段是所有产品的查询集。

我希望该字段按公司过滤产品。

如何将表单字段设置为在视图中具有动态查询集,以便根据公司ID过滤产品?

product = forms.ModelMultipleChoiceField(queryset=Product.objects.filter(company=xyz))

1 个答案:

答案 0 :(得分:1)

class EventForm(forms.Form):
    ...
    product = forms.ModelMultipleChoiceField(queryset=Product.objects.all())

    def __init__(self, *args, **kwargs):
        super(EventForm, self).__init__(*args, **kwargs)
        self.fields['product'].queryset = Product.objects.filter(company=company_id)
    # Where company_id is coming from either **kwargs or from the view.