How to Check if request.GET var is None?

First, check if the request.GET dict contains a parameter named q. You’re doing this properly already:

if request.method == 'GET' and 'q' in request.GET:

Next, check if the value of q is either None or the empty string. To do that, you can write this:

q = request.GET['q']
if q is not None and q != '':
    # Do processing here

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 the request.GET dict, so we can grab the value directly. The only time you should use the get method 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:

  • The value None evaluates to False
  • The empty string '' also evaluates to False
  • Any non-empty string evaluates to True.

So now you can write:

q = request.GET['q']
if q:
    # Do processing here

See these other resources for more details:

  • Python: Truth Value Testing
  • Python: dict.get

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)