我有设置这样的产品对象的ModelForm形式添加作为字段属性:如何在Django的ModelForm
class ProductForm(forms.ModelForm):
compositon_choices = ((2L, u'Calcium (100mg)'), (3L, u'Iron (500mg)'))
composition_selection = forms.\
MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
choices=compositon_choices)
class Meta:
model = Product
fields = [
'title', 'title_de', 'title_es', 'upc', 'description',
'description_en_gb', 'description_de',
'description_es', 'is_discountable', 'structure',
'unit_type', 'product_concentration',]
widgets = {
'structure': forms.HiddenInput()
}
在上面的例子我扩展用MultipleChoiceField所述的ModelForm通过添加composition_selection现场(这工作):
我想composoition_selection是一个形式本身,而不是只是一个MultipleChoiceField:
class ProductComponentForm(forms.Form):
component_amount = forms.IntegerField()
component_name = forms.CharField()
,然后转以这样的新形式结束ModelForm:
class ProductForm(forms.ModelForm):
composition_selection = ProductComponentForm()
class Meta:
model = Product
fields = [
'title', 'title_de', 'title_es', 'upc', 'description',
'description_en_gb', 'description_de',
'description_es', 'is_discountable', 'structure',
'unit_type', 'product_concentration',]
widgets = {
'structure': forms.HiddenInput()
}
但我无法得到这个工作。我想创建的这个ProductForm永远不会被渲染,也不会出现任何东西。我做错了什么或缺少什么?用SubForm扩展ModelForm的最佳方式是什么?
它的目的是什么?要将'ProductForm'中的'component_amount'和'component_name'作为两个字段? –
产品可以有各种产品组件。每个ProductComponent都有一个名称和一个金额。我的目标是呈现一个表单,您可以通过复选框选择各种ProductComponents,并在选择框旁边的整数字段中添加金额。 – matyas