Django CreateView内联formset实例和查询集

时间:2018-01-29 16:27:41

标签: django

所以我希望能够支付客户款项。首次呈现页面时,表单为空。我使用ajax选择客户,然后返回该客户所有未结发票的html字符串,并将其插入空表格。

当提交表单以使未完成的发票formset有效时,我需要将匹配的实例和queryset作为ajax生成的formset传递给它。我遇到的问题是将客户实例传递给get_context_data()。

现在我的客户硬编码为pk = 1并且可以确认formset是有效的。还有一个隐藏字段,其中包含表单中客户的值,但我不确定如何将其传递给get_context_data()。

任何人都知道如何做到这一点?

class PaymentCreate(CreateView):
    template_name = 'payment_create.html'
    model = Pay_hdr
    success_url = reverse_lazy('payments')
    form_class = PaymentHeadForm

    def get_context_data(self, **kwargs):
        context = super(PaymentCreate, self).get_context_data(**kwargs)
        context['customers'] = Customer.objects.all().order_by('name')
        if self.request.POST:
            customer = Customer.objects.get(pk=1)  # need to replace this line
            queryset = Accounts_receivable.objects.filter(customer=customer).exclude(balance=0).order_by('-date_trans')
            context['user'] = self.request.user
            context['formset'] = ARLineFormset(self.request.POST, instance=customer, queryset=queryset)
        else:
            context['formset'] = ARLineFormset()
        return context

    def form_valid(self, form):
        context = self.get_context_data()
        user = context['user']
        formset = context['formset']
        if form.is_valid() and formset.is_valid():
            head = form.save(commit=False)
            invoices = formset.save(commit=False)
            head.created_by = user
            head.save()
            for invoice in invoices:
                if invoice.temp_amount > 0:
                    invoice.process_payment(head, invoice.temp_amount, user)
            return redirect(self.success_url)
        else:
            return render(self.request, self.template_name, self.get_context_data(form=form))

def ajax_payment_choose_customer(request):
    customer_id = request.GET.get('customer_id', None)
    customer = Customer.objects.get(pk=customer_id)
    outstanding = Accounts_receivable.objects.filter(customer=customer).exclude(balance=0).order_by('-date_trans')
    if request.is_ajax():
        form = PaymentHeadForm()
        formset = ARLineFormset(instance=customer, queryset=outstanding)
        context = {
            'customer': customer,
            'form': form,
            'outstanding': outstanding,
            'formset': formset
        }
        html = render_to_string('payment_insert_forms.html', context)
        return HttpResponse(html)

1 个答案:

答案 0 :(得分:0)

替换customer = Customer.objects.get(pk=1)

customer = Customer.objects.get(pk=self.request.POST.get('customer'))