Django - 保存一个新的table1.PK和table2.PK和table2.FK

时间:2014-10-17 15:48:53

标签: python django django-crispy-forms

我根据django-crispy形式创建了2个表单。

  1. Form1显示OrderHeader
  2. Form2以formset
  3. 显示OrderLines

    当我打开现有的OrderHeader时,我会看到Header和Lines,我可以调整并保存打开的表单。

    当我打开表格为空时,我在OrderHeader中选择一个客户,然后添加一些订单行,但在这里我无法保存,因为OrderLine没有OrderLine.orderheader的FK值。

    问:当我点击提交时,如何在OrderLine.orderheader中保存OrderHeader.pk?

    我的views.py

    def orderline_formset(request, id=None):
        if id:
            orderid = OrderHeader.objects.get(pk=id)
        else:
            orderid = OrderHeader()
    
        OrderLineFormSet = inlineformset_factory(OrderHeader, OrderLine, OrderLineForm, extra = 1, can_delete=True)  
    
        form = OrderHeaderForm(instance=orderid)
        formset = OrderLineFormSet(instance=orderid)
        helper = OrderLineFormSetHelper()
    
        if request.method == 'POST':
            OrderLine.orderheader = orderid
            formset = OrderLineFormSet(request.POST,instance=orderid)
            if formset.is_valid():
                formset.save()
                messages.success(request, 'Order saved succesfully!')
            else:
                messages.error(request, 'Order save error, please check fields below')
        else:
            formset = OrderLineFormSet(instance=orderid)
    
        return render_to_response("order.html", {'orderform' : form,'formset': formset, 'helper': helper},
                                  context_instance=RequestContext(request))
    

    我的forms.py

    class OrderHeaderForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super(OrderHeaderForm, self).__init__(*args, **kwargs)
            self.helper = FormHelper(self)
            self.helper.form_tag = False
    
        class Meta:
            model = OrderHeader
    
    
    class OrderLineForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super(OrderLineForm, self).__init__(*args, **kwargs)
    
        class Meta:
            model = OrderLine
    
    
    class OrderLineFormSetHelper(FormHelper):
        def __init__(self, *args, **kwargs):
            super(OrderLineFormSetHelper, self).__init__(*args, **kwargs)
            self.form_method = 'post'
            self.template = 'bootstrap3/table_inline_formset.html'
            self.render_required_fields = True
            self.form_tag = False
    

1 个答案:

答案 0 :(得分:0)

错误是我只保存了formset而不是表单。所以我将views.py更改为以下内容;

if request.method == 'POST':
    form = OrderHeaderForm(request.POST,instance=orderid)
    formset = OrderLineFormSet(request.POST,instance=orderid)
    if form.is_valid() and formset.is_valid():
        form.save()
        formset.save()
        messages.success(request, 'Order saved succesfully!')