首页 文章

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

提问于
浏览
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)

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

我希望该领域按公司过滤产品 .

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

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

1 回答

  • 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.
    

相关问题