Django提交多种表格

时间:2015-04-21 13:07:31

标签: html django forms postgresql

大家好我对表格有疑问。我有两个模型,其中一个模型在不同的模型上有3个相关的ForeignKeys。在下面的例子中将显示代码。 问题是第一个表单是提交确定,并插入到数据库工作。但下一个表格不会提交。不知道我做错了什么。

模型

class OutgoingInvoice(models.Model):
    id = models.AutoField(primary_key=True)
    invoice_number = models.IntegerField()
    date = models.DateField()
    time = models.TimeField()
    place = models.CharField(max_length=255)
    status = models.CharField(max_length=255)
    due_date = models.DateField()
    total_invoice_amount = models.DecimalField(decimal_places=5, max_digits=255)
    vat_amount = models.DecimalField(decimal_places=5, max_digits=255)
    invoice_amount = models.DecimalField(decimal_places=5, max_digits=255)
    discount = models.DecimalField(decimal_places=5, max_digits=255)
    user_id = models.ForeignKey('IzibiziUser')
    organization_id = models.ForeignKey('IzibiziOrganization')
    customer_id = models.ForeignKey('OrganizationInfo')

    def __str__(self):
        return str(self.id)

表单

新的付款发票

class InsertNewCustomer(forms.ModelForm):
    name        = forms.RegexField(regex=r'\w+',  label=_('Klijent'),widget   = forms.TextInput({'class':'form-control', 'placeholder':'Klijent'}))
    oib         = forms.RegexField(regex=r'\d.+', label=_('OIB'),widget  = forms.TextInput({'class':'form-control', 'placeholder':'OIB'} ))
    address     = forms.RegexField(regex=r'\w+',  label=_('Adresa'), widget  = forms.TextInput({'class':'form-control', 'placeholder':'Adresa'}))
    city        = forms.RegexField(regex=r'\w+',  label=_('Grad'), widget  = forms.TextInput({'class':'form-control', 'placeholder':'Grad'}))
    postal_code = forms.RegexField(regex=r'\w+',  label=_('Poštanski broj'),widget  = forms.TextInput({'class':'form-control', 'placeholder':'Poštanski broj'}))


    @property
    def clean_form(self):
        try:
            obj = OrganizationInfo.object.get(oib__iexact=self.cleaned_data['oib'])
        except OrganizationInfo.DoesNotExist:
            return self.clean_form

    class Meta:
        model = OrganizationInfo
        fields = ('name', 'oib', 'address', 'city', 'postal_code',)
        exclude = (
            'country', 'phone', 'email', 'iban', 'webpage', 'delivery_address', 'delivery_city', 'delivery_postal_code',
            'delivery_country', )


class OutNewInovice(forms.ModelForm):
    date           = forms.RegexField(regex=r'\w+', label=_('Datum računa'), widget  = forms.TextInput({'class':'form-control date-now', 'placeholder':'Datum računa'}))
    due_date       = forms.DateField(label=_('Datum dospjeća'), widget  = forms.TextInput({'class':'form-control', 'placeholder':'Datum dospjeća'}))
    time           = forms.RegexField(regex=r'\w+', label=_('Vrijeme'), widget  = forms.TextInput({'class':'form-control time-now', 'placeholder':'Vrijeme'}))
    status         = forms.ChoiceField(widget = forms.Select(),choices = ([('1','Neplaćeno'), ('2','Plaćeno')]), initial='1', required = True,)
    place          = forms.RegexField(regex=r'\w+',  label=_('Mjesto'), widget  = forms.TextInput({'class':'form-control', 'placeholder':'Mjesto'}))
    invoice_number = forms.RegexField(regex=r'\w+', label=_('Broj računa'), widget  = forms.TextInput({'class':'form-control', 'placeholder':'Broj računa'}))


    status.widget.attrs['class'] = 'selectpicker'
    status.widget.attrs['style'] = 'width:100%;'

    @property
    def clean_form(self):
        try:
            obj = OutgoingInvoice.object.get(status__iexact=self.cleaned_data['status'])
        except OrganizationInfo.DoesNotExist:
            return self.clean_form


    class Meta:
        model = OutgoingInvoice

        fields = ('date', 'due_date', 'time', 'status', 'place', 'invoice_number',)
        exclude = ('total_invoice_amount', 'vat_amount', 'vat_amount', 'invoice_amount', 'discount', )

查看

@login_required
@csrf_protect
def NewOutgoingInvoice(request):
    context = RequestContext(request)
    template = "novi_izlazni_racun.html"

    user_pk = request.user.pk
    org_name = OrganizationInfo.objects.filter(id=user_pk).values('name')[0]

    if request.method == 'POST':

        new_customer = InsertNewCustomer(request.POST)
        new_inovce = OutNewInovice(request.POST)

        if new_customer.is_valid():
            a = new_customer.save()

            if new_inovce.is_valid():
                wtf = OrganizationInfo.objects.filter(id=user_pk).values('id')
                uss = request.user
                b = new_inovce.save(commit=False)
                b.user_id = uss
                b.organization_id = wtf
                b.customer_id = a
                b.save()

        return HttpResponseRedirect('/novi_izlazni_racuni/')

    else:
        new_customer = InsertNewCustomer()
        new_inovce = OutNewInovice()

    variables = RequestContext(request, {
        'name': org_name,
        'new_customer': new_customer,
        'new_inovce': new_inovce,
    })

    return render_to_response(template, variables)

如果你能看到我做错了什么。提交表单时,我在表单上没有任何错误。

2 个答案:

答案 0 :(得分:1)

在对数据执行任何操作之前,您需要检查两个表单是否有效,并且只有在两个表单都有效时才重定向。这样:

    if new_customer.is_valid():
        a = new_customer.save()

        if new_inovce.is_valid():
            ...
    return HttpResponseRedirect('/novi_izlazni_racuni/')

应该是这样的:

    valid = new_customer.is_valid()
    valid = new_inovce.is_valid() and valid
    if valid:
        a = new_customer.save()
        ...
        return HttpResponseRedirect('/novi_izlazni_racuni/')

这会强制验证两种表格

答案 1 :(得分:0)