Form redirection error doesn't work

Hi, continuing to the old solved problem click here.

in this issue, I have a condition in my Model.py that just one item is related to one invoice only.

so I made this condition in the model.py

class Invoice_billing(models.Model):
    Invoce_Nbr = models.ForeignKey(Invoices, on_delete=models.CASCADE) # should be Actived
    Item_Ctra  = models.ForeignKey(contrat_items, on_delete=models.CASCADE) # should be Actived
    Unites     = models.DecimalField(max_digits=15, decimal_places=2,null=True)
    Discu      = models.DecimalField(max_digits=4, decimal_places=2, default=0)
    post_date  = models.DateTimeField(default=timezone.now)
    author     = models.ForeignKey(User,on_delete=models.CASCADE)
    def __str__(self):
        return self.Invoce_Nbr.Invoce_Nbr
    def get_absolute_url(self):
        return reverse('Contrat_detail')
    class Meta:
        ordering = ('-post_date',)
        unique_together=[['Invoce_Nbr', 'Item_Ctra']]

so when I duplicate an item it doesn’t redirect me to the same page.
it gives me this error page.

# IntegrityError at /Invoic_billing/1/

UNIQUE constraint failed: Home_invoice_billing.Invoce_Nbr_id, Home_invoice_billing.Item_Ctra_id

I want to redirect it to the same page with a message as I did in my views.py

    if request.method == 'POST':
        if request.POST.get("form_ability") == "Add":
            form2 =form(request.POST)
            if form2.is_valid():
                form2.instance.Invoce_Nbr_id= id_itm
                form2.instance.author = request.user
                form2.save()
                return redirect('Invoic_billing', id_itm)
            else:
                form_error_ablt = 'Check your inputs'

what I missed here?

In your model you have:

So this error occurs:

Because of this:

(emphasis mine)

You can’t duplicate an item because you explicitly told the database to not allow two rows where both the Invoce_Nbr and Item_Ctra are the same.

Yes Mr, I knew , but my question is how to return back to my page without save the form and without getting the page error?

You’ve got at least two different ways of handling this -

1 Like

Thank you it works with try

    if request.method == 'POST':
        if request.POST.get("form_ability") == "Add":
            form2 =form(request.POST)
            try:
                if form2.is_valid():
                    form2.instance.Invoce_Nbr_id= id_itm
                    form2.instance.author = request.user
                    form2.save()
                    return redirect('Invoic_billing', id_itm)
            except:
                form_error_ablt = 'Check your inputs "duplicated item"'