我需要从内联表单集的现有实例中保存一条新记录。我设法从父模型(Order
)保存了一个新实例,但是我不知道如何保存表单集的新实例。代码是这样的:
def order(request, date):
edit = Order.objects.get(date=date, user=None)
edit_formset = modelformset_factory(Order_items, fields='__all__', extra=0)
if request.method == 'POST':
form = OrderForm(request.POST, instance=edit)
formset = edit_formset(request.POST, queryset=Order_items.objects.filter(order__date=date))
if form.is_valid():
instance = form.save(commit=False)
instance.pk = None
instance.user_id = request.user.id
if formset.is_valid():
form.save()
formset.save()
return HttpResponseRedirect('order')
else:
form = OrderForm(instance=edit)
formset = edit_formset(queryset=Order_items.objects.filter(order__date=date))
return render(request, 'diner/order.html', {'edit': edit, 'form': form, 'formset': formset})
你可以
试试这个。
if request.method == 'POST':
form = OrderForm(request.POST, instance=edit)
formset = edit_formset(request.POST)
If form.is_valid():
instance = form.save(commit=False)
instance.pk = None
instance.user_id = request.user.id
form.save()
if formset.is_valid():
add_new = formset.save(commit=False)
add_new.instance = instance
add_new.save()
return HttpResponseRedirect('order')
因为 post 请求时,您正在 formset = edit_formset(request.POST,实例=编辑),因此在保存表单集时,它会保存旧订单的order_item,您将其命名为"编辑"而不是新订单。add_new.instance = instance将有助于创建表单集新实例。
好的,我得出了一个解决方案:
if form.is_valid():
form.cleaned_data['pk'] = None
if formset.is_valid():
create_order = Order.objects.create(date=form.cleaned_data['date'], user_id=request.user.id)
new = formset.save(commit=False)
for n in new:
n.id = None
n.order_id = create_order.id
create_order.save()
n.save()