我正在为零件创建“订单”表单。
我AddOrderForm
有Order
模型字段(如quantity
),但同时来自Part
模型(如name_in_english
)和PartNumber
模型(如number
)和其他一些字段的一些与零件相关的信息......
首先,我ModelForm
为每个人做了分离,然后他们像这样组合起来:
表格.py
class PartNumberForAddOrderForm(forms.ModelForm):
class Meta:
model = PartNumber
fields = ('number',)
class PartForAddOrderForm(forms.ModelForm):
class Meta:
model = Part
fields = ('manufacturer','name_in_english')
class AddOrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ('quantity',)
在模板中:
<form class="form-inline well" id="add_order">
<div class="row-fluid">
<div class="span12">
{% crispy form_part_number %}
{% crispy form_part %}
{% crispy form_order %}
<input type="submit" class="btn btn-primary pull-right" value="{% trans 'Add' %}"/>
</div>
</div>
</form>
有了这个观点就变成了:
form_part_number.is_valid() and form_part.is_valid() and form_order.is_valid():
所有这一切看起来都非常丑陋,而且是错误的......
所以我创建了另一种方式:
class PartForm(forms.ModelForm):
class Meta:
model = Part
fields = ('manufacturer','name_in_english')
class PartNumberForm(forms.ModelForm):
class Meta:
model = PartNumber
fields = ('number',)
class AddOrderForm(forms.ModelForm):
manufacturer = PartForm.base_fields['manufacturer']
name_in_english = PartForm.base_fields['name_in_english']
number = PartNumber.base_fields['number']
class Meta:
model = Order
fields = ('manufacturer','number','quantity','name_in_english')
问题:这是Form.base_fields['']
合法的方式吗?我认为这.save()
不起作用,但.is_valid()
应该没问题,对吧?有没有更好的方法呢?
我可以在任何地方做任何有用的事情,所以这是我自己想出的。这让我很担心。
谢谢