我想将产品ID传递给表单类,以在数据库中创建包含该商品的表单。
我的表单:
class Order_form(forms.Form):
def __init__(self, product_id,*args,**kwargs):
self.add_option = forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple, required = False, queryset=product.objects.get(id = product_id).add_option.all())
super(Order_form,self).__init__(*args,**kwargs)
上面的表格不会创建任何内容,但是此表格恰好可以创建我需要的内容。但是,我需要动态传递product_id
,而不必将1
硬编码为id:
class Order_form2(forms.Form):
add_option = forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple, required = False, queryset=product.objects.get(id = 1).add_option.all())
PS:一切正常,感谢下面的回答和评论,我的表格看起来像这样
class Order_form(forms.Form):
add_option = forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple, required = False, queryset=None)
def __init__(self, product_id,*args,**kwargs):
super(Order_form, self).__init__(*args, **kwargs)
self.fields['add_option'].queryset=product.objects.get(id = product_id).add_option.all()
答案 0 :(得分:0)
这大概是应该的样子。
class Order_form(forms.Form):
def __init__(self, product_id,*args,**kwargs):
super().__init__(product_id, *args, **kwargs) # This is the default stuff that forms.Form does
# You need to add this part so that it edits the field after creation
self.fields['add_option']= forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple, required = False, queryset=product.objects.get(id = product_id).add_option.all())
# super(Order_form,self).__init__(*args,**kwargs) this would re-overwrite it so we don't want it here
通常是在django中完成的。