From all the HTML books i've read, I know that POST should be used when changing, adding or removing from the database and when handling sensitive information like passwords. GET should be used when you just want to search through a database without making any changes. With that said, I am reading a book on Django and up until now, to handle forms, we did it like this:
def RegistrationFormView(request):
form = RegistrationForm()
if request.method == "POST": #if the user has clicked the 'submit' button on the form and is sending data
form = RegistrationForm(request.POST)
which makes sense. The book goes on to teach how to create a search page which searches through the database. For this, we use GET, which makes sense. This is the form:
class SearchForm(forms.Form):
query = forms.CharField(
label='Enter a keyword to search for',
widget=forms.TextInput(attrs={'size': 32})
)
But this is the view (and this is what confused me):
def search_page(request):
form = SearchForm()
bookmarks = []
show_results = False #Only show results if the user has searched something
if request.GET.has_key('query'): #check if the user submitted GET data
show_results = True #return results since the user has submitted GET data
query = request.GET['query'].strip()
if query:
form = SearchForm({'query' : query})
I want to clarify four things here.
1) Would it be exactly the same if I just did
if request.method == "GET":
instead of
if request.GET.has_key('query'):
2) in the line
if request.GET.has_key('query'):
according to the Djangobook, it says "has_key Returns True or False, designating whether request.GET or request.POST has the given key." Now, what exactly is a 'key'? Is a key a field in the form, and
if request.GET.has_key('query'):
checks to see if the user has filled out the formField which is called 'query'?
3) Am I allowed to call form.is_valid() when the method is GET? Because what I was thinking was doing
form = SearchForm(request.GET)
if form.is_valid():
query = form.cleaned_data['query']
Is that allowed?
4) why does the book do
if query:
after
query = request.GET['query'].strip()
? Doesn't the line
if request.GET.has_key('query'):
already verify that the 'query' field is filled in?
No. if request.method == "GET":
is in no way equivalent to if request.GET.has_key('query'):
request.GET
and request.POST
are dictionary subclasses and has_key
is part of the built-in dictionary interface http://docs.python.org/2/library/stdtypes.html#dict.has_key however it is deprecated in favor of 'query' in request.GET
.
Forms do not care about the request method or that there is a request at all. Forms validate dictionaries whatever the source might be.
In the case of ?query=
or ?query=%20
the key query
would evaluate to ''
and ' '
which would both be False
after running through strip()
. if request.GET.has_key('query'):
only checks that the key is present and does not look at the value.