Marin
Marin

Reputation: 1121

Django submit multipy forms

Hi guys I have question about forms. I have two models where one model has 3 related ForeignKeys on differnt models. In example below will be displayed code. The question is first form is submited ok, and insert to database works. But next form wont submitt. Don't know what I'm doing wrong.

Models

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)

Forms

New Outgoing Invoice

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', )

View

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

If you coul see where I'm doing wrong. I dont get any error on form when form is submitted.

Upvotes: 0

Views: 52

Answers (2)

shalakhin
shalakhin

Reputation: 4866

I think here is the answer to your question:

https://docs.djangoproject.com/en/1.8/ref/forms/api/#django.forms.Form.prefix

Upvotes: 0

Iain Shelvington
Iain Shelvington

Reputation: 32294

You need to check if both forms are valid before performing any action on the data AND only redirect if both forms are valid. This:

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

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

Should be this:

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

This forces both forms to be validated

Upvotes: 1

Related Questions