28

It seems I can't make this example print "You submitted nothing!". Every time I submit an empty form it says:

You submitted: u''

instead of:

You submitted nothing!

Where did I go wrong?

views.py

def search(request):
    if 'q' in request.GET:
        message = 'You submitted: %r' % request.GET['q']
    else:
        message = 'You submitted nothing!'

    return HttpResponse(message)

template:

<html>
    <head>
        <title> Search </title>
    </head>
    <body>
        <form action="/search/"  method="get" >
        <input type="text" name = "q">
        <input type="submit"value="Search"/>
        </form>
    </body>
</html>
Dharman
  • 30,962
  • 25
  • 85
  • 135
MacPython
  • 17,901
  • 10
  • 42
  • 48

8 Answers8

52

Calling /search/ should result in "you submitted nothing", but calling /search/?q= on the other hand should result in "you submitted u''"

Browsers have to add the q= even when it's empty, because they have to include all fields which are part of the form. Only if you do some DOM manipulation in Javascript (or a custom javascript submit action), you might get such a behavior, but only if the user has javascript enabled. So you should probably simply test for non-empty strings, e.g:

if request.GET.get('q'):
    message = 'You submitted: %r' % request.GET['q']
else:
    message = 'You submitted nothing!'
tux21b
  • 90,183
  • 16
  • 117
  • 101
  • 1
    Wouldn't this throw exception if q does not exists in dict? – Davor Lucic Aug 17 '10 at 09:16
  • 9
    No, calling `dict.get(key, default=None)` will either return the value stored for the key, or the default otherwise. In that case `None` is returned and both, `u''` and `None` evaluate to `False`. So, get() is a useful method when you don't want an exception to be thrown. – tux21b Aug 17 '10 at 09:27
  • Oooh! You are right, not sure what I was thinking this morning. – Davor Lucic Aug 17 '10 at 10:36
  • Ok. Thanks. Not sure what the second get is doing here. But it worked. So I will find out now. – MacPython Aug 17 '10 at 10:41
  • The second get is a python dictionary method to avoid throwing an exception when looking for a key that doesn't exist . Have a look : https://imgur.com/a/0rp4Z36 – Mossab Jan 06 '22 at 21:12
17
q = request.GET.get("q", None)
if q:
    message = 'q= %s' % q
else:
    message = 'Empty'
Davor Lucic
  • 28,970
  • 8
  • 66
  • 76
2

since your form has a field called 'q', leaving it blank still sends an empty string.

try

if 'q' in request.GET and request.GET['q'] != "" :
     message
else
     error message
second
  • 28,029
  • 7
  • 75
  • 76
2

In python, None, 0, ""(empty string), False are all accepted None.

So:

if request.GET['q']: // true if q contains anything but not ""
    message
else : //// since this returns "" ant this is equals to None
    error
Mp0int
  • 18,172
  • 15
  • 83
  • 114
1

Here is a good way to do it.

from django.utils.datastructures import MultiValueDictKeyError
try:
    message = 'You submitted: %r' % request.GET['q']
except MultiValueDictKeyError:
    message = 'You submitted nothing!'

You don't need to check again if q is in GET request. The call in the QueryDict.get already does that to you.

joaonrb
  • 965
  • 11
  • 30
1
from django.http import QueryDict

def search(request):
if request.GET.\__contains__("q"):
    message = 'You submitted: %r' % request.GET['q']
else:
    message = 'You submitted nothing!'
return HttpResponse(message)

Use this way, django offical document recommended __contains__ method. See https://docs.djangoproject.com/en/1.9/ref/request-response/

Idos
  • 15,053
  • 14
  • 60
  • 75
0
def search(request):
if 'q' in request.GET.keys():
    message = 'You submitted: %r' % request.GET['q']
else:
    message = 'You submitted nothing!'

return HttpResponse(message)

you can use if ... in too.

7i11
  • 96
  • 6
0
msg = request.GET.get('q','default')
if (msg == default):
    message = "YOU SUBMITTED NOTHING"
else: 
    message = "you submitted = %s" %msg"
return HttpResponse(message);