I’m getting into django and this is getting me a headache. I’m trying to get a simple GET variable. URL is site.com/search/?q=search-term
My view is:
def search(request):
if request.method == 'GET' and 'q' in request.GET:
q = request.GET.get('q', None)
if q is not None:
results = Task.objects.filter(
Q(title__contains=q)
|
Q(description__contains=q),
)
...return...
else:
...
else:
...
Search queries like mysite.com/search/? (without q) get through the first if correctly.
The problem is in queries like mysite.com/search/?q=. They don’t get caught by if q is not None:
So, the short answer would be How can I check q == None? (I’ve already tried '', None, etc, to no avail.)
First, check if the
request.GETdict contains a parameter namedq. You’re doing this properly already:Next, check if the value of
qis eitherNoneor the empty string. To do that, you can write this:Notice that it is not necessary to write
request.GET.get('q', None). We’ve already checked to make sure there is a'q'key inside therequest.GETdict, so we can grab the value directly. The only time you should use thegetmethod is if you’re not sure a dict has a certain key and want to avoid raising a KeyError exception.However, there is an even better solution based on the following facts:
Noneevaluates toFalse''also evaluates toFalseTrue.So now you can write:
See these other resources for more details:
dict.get