2017-03-06 94 views
0
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) 

我有一个表单,它有一个产品字段,它是所有产品的查询集。Django表单字段动态查询集字段

我希望该领域能够按公司过滤产品。

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

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

回答

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. 
+0

感谢您的帮助。我得到一个__init __()有一个意外的关键字参数'company_id'错误。代码形式如下: def __init __(self,company_id,* args,** kwargs): self.id = company_id super(EventForm,self).__ init __(* args,** kwargs) self。字段['product']。queryset = Product.objects.filter(company__id = id)。 代码鉴于:form_class = CompanyForm(COMPANY_ID = ID) – user1778568

+0

你超载'EventForm' init,但是之后使用'CompanyForm'? –

+0

谢谢堆。有用。 – user1778568