我有一个这样的表单:
class ThingSelectionForm(forms.Form):
things = forms.ModelChoiceField(
queryset=Product.objects.filter(product=my_product),
widget=forms.RadioSelect,
empty_label=None,
)我的问题是-当页面加载时,我如何传入my_product变量?我应该创建一个自定义的__init__方法吗?
任何帮助都非常感谢。
发布于 2012-12-06 14:28:50
我今天就是在做这样的事情。我找到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())发布于 2012-12-06 05:55:11
可以,您可以覆盖初始化
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)https://stackoverflow.com/questions/13733110
复制相似问题