I have this view function:
def search(request):
if request.method == 'GET':
form = SearchForm(request.GET)
if form.is_valid():
last_name = form.cleaned_data['last_name']
first_name = form.cleaned_data['first_name']
lawyers = Lawyer.objects.all()
[ other if statements ]
....
else:
form = SearchForm()
return render_to_response('search.html', {'form': form})
I would think that when the page loads the else statement will be executed with the initial blank form. But this is not the case. To have the form displayed initially I have to add it inside the first if:
def search(request):
if request.method == 'GET':
form = SearchForm(request.GET)
if form.is_valid():
last_name = form.cleaned_data['last_name']
first_name = form.cleaned_data['first_name']
lawyers = Lawyer.objects.all()
[ other if statements ]
....
form = SearchForm()
return render_to_response('search.html', {'form': form})
else:
form = SearchForm()
return render_to_response('search.html', {'form': form})
Can you help why the first if is never false? Thank you.
The entire view function is here
When you post a form with
method=GETyou don’t actually change the method from the initial request: it wasmethod=GETtoo.You can either use
method=POSTin your form, and your if statement will check for that, or you could check for the existence of the required fields,first_name,last_nameor both, as your form requires.You might want to abstract this into the form itself, modifying the
__init__method, but you don’t have to.