views:

65

answers:

3

Code:

# it's an ajax request, so parameters are passed via GET method
def my_view(request):
    my_param = request.GET['param'] // should I check for KeyError exception?

In PHP Frameworks I typically have to check for parameter to exists and redirect user somewhere if it does not. But in Django unexisted parameter results in 500 error page and it seems desired behaviour. So is it ok to leave code as is or there is a better practic? Should I always use standard params passing like /myaction/paramvalue/ instead of /myaction?param_name=param_value (it's kinda hard to build such URLs for ajax requests)?

A: 

Yes, you should check for KeyError in that case. Or you could do this:

if 'param' in request.GET:
    my_param = request.GET['param']
else:
    my_param = default_value
Mike DeSimone
+3  A: 

Your server should never produce a 500 error page.

You can avoid the error by using:

my_param = request.GET.get('param', default_value)

or:

my_param = request.GET.get('param')
if my_param is None:
    return HttpResponseBadRequest()
Ned Batchelder
btw try ... except block seems to be better in case I have several parameters (1 except block insteat of several checks for None).
glss
Yes, true. You may also find you have to do more specific checks on parameters individually for proper range of values, compatibility between parameters, and so on.
Ned Batchelder
I use django forms to validate the input, even for ajax calls. It's easier to use if you have many input parameters, and it does most of the work for you.
OmerGertel
A: 

How about passing default value if param doesn't exist ?

my_param = request.GET.get('param', 'defaultvalue')
Srikanth Chundi
defaultvalue is not often available.
glss