@
yueyoum ```
ItemFormSet = forms.models.inlineformset_factory(
Order, Item,
)
class AddOrderView(CreateView):
template_name = 'new_order.html'
form_class = OrderForm
def get_context_data(self, **kwargs):
context = super(AddOrderView, self).get_context_data(**kwargs)
if
self.request.POST:
context['item_formset'] = ItemFormSet(
self.request.POST)
else:
context['item_formset'] = ItemFormSet()
return context
def formset_invalid(self, form):
return self.render_to_response(self.get_context_data(form=form))
def form_valid(self, form):
context = self.get_context_data()
formset = context['item_formset']
if formset.is_valid():
self.object = form.save(self.request.user)
# set the order_fk for items
formset.instance = self.object
formset.save()
return redirect(reverse('core:list_orders'))
else:
self.formset_invalid(form)
# 在存储Item(项目)的时候,自动设置其位于Order(订单)中的序号。
```