Django validate and go back to preview URL?
-
12-09-2019 - |
Question
im asking again :), i don't know how make this.
My English is not too good, but ill try to asking this:
how ill validate a form and go back to the preview url (the same view form) and show the validation errors?, im asking this because i have 2 form's, the first form's action is going to a second form (POST), but in this second form (view?) i need to validate the first form, if the first form is valid i want to show the second form else ill show the first form with errors.
i dont know if im clear , im sorry.
im thinking about this:
def secondForm(request):
if request.method =='POST':
form = FirstForm(request.POST)
if form.is_valid():
fields = request.POST.copy()
# showing the second form?? with x differents fields, i have 2.
if fields['xvalue']=='1': # this is from radio buttons
form2 = xSecondForm()
elif fields['xvalue']=='2':
form2 = ySecondForm()
else:
# here go back with erros msgs????
#return render_to_response('firstFormTemplate.html',{'form': form}, context_instance=RequestContext(request))
else:
#return something or go back ???
Thanks guys PD: im happy, im coding Django + python :D
Solution
Yes, formwizard might be your answer, but you could probably do it with some logic in a view.
Something like:
def your_view(request):
context = {}
data = request.method == 'POST' and request.POST or None
form = FirstForm(data=data)
# If the first form is valid, build the second.
if form.is_valid():
if form.cleaned_data['xvalue'] == 1:
form2 = xSecondForm(data=data)
else:
form2 = ySecondForm(data=data)
context['form2'] = form2
# If both forms are valid, everything is done.
if form.is_valid() and form2.is_valid():
# TODO: put save/processing logic here
# Now redirect.
return http.HttpResponseRedirect(...)
# If we get here, either there hasn't been a post yet, the second form hasn't
# been entered, or there was an error in either form.
context['form'] = form
return render_to_response(...)
OTHER TIPS
Ok, guys, i think that mi solution is FormWizard :)
but im not clear with something about my Second Form, because i need to show the second form in different way if the selected option in radio is for more or less fields (in the second form)
;(
I think you want to use process_step() to do some logic on how/what do display in your second form.