Q:

Submitting empty form and weird output

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 was an example..

A:

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.

A:

'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'] != '':

