Django 动态模型选择形式



>我有一个这样的形式:

class ThingSelectionForm(forms.Form):
    things = forms.ModelChoiceField(
        queryset=Product.objects.filter(product=my_product),
        widget=forms.RadioSelect,
        empty_label=None,
    )

我的问题是 - 页面加载时如何传入 my_product 变量?我应该创建自定义__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)

我用过滤器(foo=bar)类型查询做了我的。

然后在 forms.py

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

最新更新