views:

26

answers:

2

Hello,

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

+2  A: 

Every normal HTTP request (like when you go to http://stackoverflow.com) is a GET request. It is generally a good idea to use POST as the method of your forms when they change some data.

You should read: http://stackoverflow.com/questions/46585/when-do-you-use-post-and-when-do-you-use-get

olt
Thanks. I am reading it.
Zeynel
+1  A: 

When you post a form with method=GET you don't actually change the method from the initial request: it was method=GET too.

You can either use method=POST in your form, and your if statement will check for that, or you could check for the existence of the required fields, first_name, last_name or both, as your form requires.

if 'first_name' in request.GET or 'last_name' in request.GET:
    form = SearchForm(request.GET)
else:
    form = SearchForm()

You might want to abstract this into the form itself, modifying the __init__ method, but you don't have to.

Will Hardy