Django动态模型选择表

时间:2012-12-05 21:51:41

标签: 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变量?我应该创建自定义__init__方法吗?

任何帮助都非常感激。

2 个答案:

答案 0 :(得分:3)

是的,您可以覆盖 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)

答案 1 :(得分:1)

我今天正在做这样的事情。我找到了this to be helpful。这是戴夫的答案

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())
相关问题