Render multiple forms and validate them in a single template in DJANGO

1

I tried to render 3 forms with Class-based views in a single template but I did not succeed, so I decided to do something like this with a method: def formTortas(request): ....
where I call my 3 forms defended in Forms.py in this way,

    formVenta = VentaForm()
    formTorta = TortaForm()
    formCliente = ClienteForm()

and I return to my sight like this

return render(request, "tienda/venta_tortas.html", {'formVentaTorta':formVenta,'formTorta': formTorta, 'formCliente': formCliente})

Normally I can access the 3 forms, and to process the content of each form I do it with conditions and I receive their values from a Form for example. of Sales: formVenta = VentaForm(request.POST, request.FILES) , if the User has filled all the COMPULSORY fields of a Form it is inserted with SUCCESS. The problem arises for example when you do not fill in the required fields of a form and normally you should return the message VALIDATION error, and I no longer return the ERROR of the validations, due to the fact that the two forms no longer re-render , I get this error, for example when I try to insert formVenta .

local variable 'formTorta' referenced before assignment

Each form assigns a variable in the conditions (even try to assign in a global variable but follows ..), how to re-render to all Forms for example after validating errors of any of the forms? or some other more efficient method that I can use ?, Thanks.

    
asked by Alex Ancco Cahuana 06.04.2017 в 19:59
source

1 answer

2

The solution was to initialize all the forms at the top of the function something like this,
def formTortas(request):
form_venta = VentaForm() formTorta = TortaForm() formCliente = ClienteForm() if request.method == "POST": ...... .....

in both the ELSE part of the If of Form_valid

else:
    form_venta = VentaForm()
    formTorta = TortaForm()
    formCliente = ClienteForm()

and something like this would be the return of the forms

return render(request, "tienda/venta_tortas.html", {'form_venta_torta': form_venta,
                                                    'formTorta': formTorta, 'formCliente': formCliente})

Greetings

    
answered by 11.05.2017 / 22:59
source