2017-03-06 111 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