从formset实例

时间:2017-01-14 09:59:13

标签: python django inline-formset

我需要从内联formset的exitsing实例中保存一条新记录。我设法从父模型(Order)保存了一个新实例,但我无法弄清楚如何保存一个新的formset实例。代码是这样的:

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})

2 个答案:

答案 0 :(得分:0)

你可以试试这个。

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)中定义实例,因此在保存formset时,它会将order_item保存为您命名为&的旧订单#39;编辑'不是新的。 add_new.instance = instance 将有助于创建formset新实例。

答案 1 :(得分:0)

好的,我已经找到了解决方案:

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()