从 formset 实例中保存一条新记录

Save a new record from formset instance

我需要从现有的内联表单集实例中保存一条新记录。我设法从父模型 (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, instance=edit) 中定义实例,因此在保存时表单集将 order_item 保存为您命名为 'edit' 的旧订单,而不是新订单。 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()