Django动态模型选择表

Django动态模型选择表,django,django-forms,Django,Django Forms,我有一张这样的表格: class ThingSelectionForm(forms.Form): things = forms.ModelChoiceField( queryset=Product.objects.filter(product=my_product), widget=forms.RadioSelect, empty_label=None, ) 我的问题是-加载页面时如何传入My_product变量?我应该创建一个自

我有一张这样的表格:

class ThingSelectionForm(forms.Form):
    things = forms.ModelChoiceField(
        queryset=Product.objects.filter(product=my_product),
        widget=forms.RadioSelect,
        empty_label=None,
    )
我的问题是-加载页面时如何传入
My_product
变量?我应该创建一个自定义的
\uuuuu init\uuuu
方法吗


非常感谢您的帮助。

是的,您可以覆盖init

    class ThingSelectionForm(forms.Form):
        things = forms.ModelChoiceField(
            widget=forms.RadioSelect,
            empty_label=None,
        )
       def __init__(self, *args, **kwargs):
              my_prod = kwargs.pop('my_prod), None
              super(...)
              self.fields['things'].queryset = Product.objects.filter(product=my_prod),

#view

form = ThingSelectionForm(my_prod = my_prod)

是的,您可以覆盖init

    class ThingSelectionForm(forms.Form):
        things = forms.ModelChoiceField(
            widget=forms.RadioSelect,
            empty_label=None,
        )
       def __init__(self, *args, **kwargs):
              my_prod = kwargs.pop('my_prod), None
              super(...)
              self.fields['things'].queryset = Product.objects.filter(product=my_prod),

#view

form = ThingSelectionForm(my_prod = my_prod)

我今天只是在做这样的事情。我找到了。这是戴夫的回答

models.py

class Bike(models.Model):
    made_at = models.ForeignKey(Factory)
    added_on = models.DateField(auto_add_now=True)
view.py

form  = BikeForm()
form.fields["made_at"].queryset = Factory.objects.filter(user__factory)
我用一个filter(foo=bar)类型的查询完成了我的任务

然后在forms.py中

made_at = forms.ModelChoiceField(queryset=Factory.objects.all())

我今天只是在做这样的事情。我找到了。这是戴夫的回答

models.py

class Bike(models.Model):
    made_at = models.ForeignKey(Factory)
    added_on = models.DateField(auto_add_now=True)
view.py

form  = BikeForm()
form.fields["made_at"].queryset = Factory.objects.filter(user__factory)
我用一个filter(foo=bar)类型的查询完成了我的任务

然后在forms.py中

made_at = forms.ModelChoiceField(queryset=Factory.objects.all())