Django形式get_or_create

时间:2015-04-22 09:51:35

标签: python django forms models

如何在表单保存上gat对象ID。问题是,如果对象存在于数据库中我只是返回对象并将其保存到其他形式比较表单中的值,否则我想在数据库中保存新对象。下面是我的exmaple代码,所以如果你可以看看。

forms.py

@login_required
@csrf_protect
def NewOutgoingInvoice(request):

    template = "novi_izlazni_racun.html"
    user_pk = request.user.id
    org_name = OrganizationInfo.objects.filter(id=user_pk).values('name')[0]
    org_id = request.user.organization_id

    if request.method == 'POST':
        form1 = InsertNewCustomer(request.POST)
        form2 = Outdrew(request.POST, request.user)
        if form1.is_valid() and form2.is_valid():
            a, created = OrganizationInfo.objects.get(oib__exact=cleaned_data['oib'])
            if created:
                b = form2.save(commit=False)
                b.user_id = request.user
                b.organization_id = org_id
                b.customer_id = created
                b.save()
                return HttpResponseRedirect('/novi_izlazni_racuni/')
            else:
                a = form1.save()
                b = form2.save(commit=False)
                b.user_id = request.user
                b.organization_id = org_id
                b.customer_id = a
                b.save()
                return HttpResponseRedirect('/novi_izlazni_racuni/')

    else:
        form1 = InsertNewCustomer()
        form2 = Outdrew()

    variables = RequestContext(request, dict(name=org_name, form1=form1, form2=form2))

    return render_to_response(template, variables)

0 个答案:

没有答案