1

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..

Marijus
  • 4,195
  • 15
  • 52
  • 87

4 Answers4

3

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.

Jake
  • 2,515
  • 5
  • 26
  • 41
2

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.

Aaron Dufour
  • 17,288
  • 1
  • 47
  • 69
  • Thank you so much for a great explanation! I was having the same problem. I just have something to add. By adding %s as the place holder in the above statement that fixed both of the problems which is VERY weird since that statement should not be even EVALUATED according to the if statement..... right?? – BluePython Sep 10 '13 at 09:27
  • @Prussian You're right, that doesn't make much sense. Are you sure nothing else changed? – Aaron Dufour Sep 10 '13 at 15:02
  • absolutely nothing (pretty much 100% certain, I did not change anything else, since I was implementing your advise quite literally). I am using version 1.4 of Django by the way. I must admit it was quite annoying to see that happen, but the fact that it was working prevented me from looking at it in more detail. At least for now. – BluePython Sep 10 '13 at 17:03
1

'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'] != '':
jpichon
  • 26
  • 1
  • 2
1

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'
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245