Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect in Django with form errors?

In my project, I have an order detail page. This page has multiple forms (return order, deliver order etc.)

Each of this forms are handled using different views.

For example returning order form has action which calls order_return view which then, if ReturnOrderForm is valid, redirects back to order_detail.

The problem is when there are errors in the ReturnOrderForm. I would like to get back to order_detail and show the errors.

For now, I just render order_detail inside the order_return view in case there are errors, which works good but the url isn't changed to order_detail url. I would use HttpResponseRedirect but I have no idea how to handle errors.

Do you have any ideas?

def order_return(request):
    return_order_form = ReturnOrderForm(request.POST or None)
    order_id = request.POST.get('order_id')
    order = Job.objects.get(id=order_id)

    if request.method == 'POST':
        if return_order_form.is_valid():
            ...
            order.delivery.return_delivery(notes=customer_notes)
            return HttpResponseRedirect(reverse("order_detail", args=(order_id,)))

    return render(request, "ordersapp/order_detail/order-detail.html",
                  context={'return_order_form': return_order_form,
                           ...})
like image 258
Milano Avatar asked Nov 09 '22 02:11

Milano


1 Answers

You can make a shared method that can return the detail response

def get_order_detail_response(request, contxt=None, **kwargs)
     context = contxt or {}
     context['return_order_form'] = kwargs.get('return_form', ReturnOrderForm())
     return render(request, 'template', context)

Each view will then be able to return this

return get_order_detail_response(request, return_form=return_order_form)
like image 121
Sayse Avatar answered Dec 03 '22 08:12

Sayse