On 31 Dec 2009, at 10:58 , BobAalsma wrote: > > I'm following the Django book to learn Django. I'm getting unexpected > responses and can't find how to address this. It seems that submitting > an empty form is not handled as if it is empty ?? > > In views.py: > def search(request): > if 'q' in request.GET: > message = 'U zocht: %r' % request.GET['q'] > else: > message = 'Leeg' > return HttpResponse(message) > > However, on submitting an empty form, the displayed message is: > U zocht: u'' > > On submitting a 'd', the answer is: > U zocht: u'd' > > Consistent, that's the good news... > > How to solve this?
First of all, this has nothing to do with forms. "Forms" in a Django context designates Django Forms: http://docs.djangoproject.com/en/dev/topics/forms/. Here, you're only playing with query parameters, forms are not involved. Second, this is a Python issue more than a Django one: even if the parameter is empty (e.g. `yourpage.com/search?q=`) it is present, therefore it will be put in the GET dictionary. `key in dict` only checks that the key exists, not that it keys to a value (let alone a "falsy" value such as an empty string). What you really want to check is that the 'q' key exists *and is non-empty*. I suggest that you use the `dict.get` method for this: it returns the value for the key if the key exists, None if it doesn't. Just replace `'q' in request.GET` by `request.GET.get('q')` and you should have the behavior you expect. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

