Here's my form :
<form action = "/search/" method = "get">
<input type = "text" name = "q">
<input type = "submit" value = "Search">
</form>
And here's my view:
def search(request):
if 'q' in request.GET:
message = 'You searched for: %r' % request.GET['q']
else:
message = 'You submitted an empty form :('
return HttpResponse(message)
When I try to input something everything works fine, except for weird u' ' thing. For example when I enter asdasda I get the output You searched for: u'asdsa'
. Another problem is that when I submit an empty form the output is simply u''
, when it should be "You submitted an empty form :(". I'm reading "The Django Book", the 1.x.x version and this wa开发者_如何学Cs an example..
The "weird u thing" is a unicode string. You can read about it here: http://docs.python.org/tutorial/introduction.html#unicode-strings
And I'm guessing since the user pressed submit, you get a request that has an empty q value (u'') since the user didn't enter anything. That makes sense, right? You should change your if statement to check for this empty unicode string.
For the first problem, try using %s
instead of %r
. What you're doing is 'raw' formatting, which, when the string is unicode, tells you that. Normal string formatting will just copy the value without the 'u' or quotes.
For the second problem, a text input will always have the key in the dictionary. Instead of you if
statement, try:
if request.GET['q'] != "":
to test if the string is empty.
'q' is present in the request.GET dictionary after the form is submitted, it just happens to be empty in that case. Try this, to show the error message when submitting an empty query:
if 'q' in request.GET and request.GET['q'] != '':
The strange u
is due to the %r
which calls repr
-- use %s
instead.
>>>'%r' % u'foo'
[out] "u'foo'"
>>>'%s' % u'foo'
[out] u'foo'
精彩评论