Hi Stackoverflow people,
I am irritated by the the Django Form handling, if the form submits to new page and the form validation fails. I intended to return to the earlier submitted form, and display the error message for correction.
The error message will be displayed, but the url link is not changing.
How can I change the *else statement of the is_valid() statement*, in order to redirect to the earlier form?
Thank you for your advice!
urls.py
urlpatterns = patterns("",
url(r"^add/$", "remap.views.add_project", name="add_project_location"),
url(r"^add/details/$", "remap.views.add_project_details", name="add_project_details"),
)
views.py
def add_project_details(request):
if request.method == 'POST': # If the form has been submitted...
locationForm = LocationForm(request.POST)
if locationForm.is_valid(): # All validation rules pass
locality = locationForm.cleaned_data['locality']
state = locationForm.cleaned_data['state']
country = locationForm.cleaned_data['country']
projectForm = ProjectForm(initial = {
'locality': locality,
'state': state,
'country': country,
})
return render_to_response('map/add_project_details.html', {
'projectForm': projectForm,
}, context_instance = RequestContext(request))
else:
print locationForm.errors
return render_to_response('map/add_project_location.html', {
'locationForm': locationForm,
}, context_instance = RequestContext(request))
else:
return HttpResponseRedirect('../') # Redirect to the location reg if site is requested w/o proper location
There’s no cause to get irritated about Django doing exactly what it is designed to do.
Your redirect is on the
elseclause corresponding toif request.method == 'POST'. So, it will only take effect if this is not a form submission. In other words, that view will never actually display an empty form.Then, depending on whether or not the POSTed form is valid, you display one of two templates. You’re not doing any redirecting at this point.
However, even if you had asked Django to redirect when the form is invalid, I doubt you would get the result you want. This is because the rules of HTTP (not Django) say that you can’t redirect a POST – so your request to the redirected view would be a GET, without any of the invalid data or error messages.