Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: request.GET and KeyError

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)?

like image 898
glss Avatar asked Oct 02 '10 12:10

glss


1 Answers

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() 
like image 86
Ned Batchelder Avatar answered Sep 20 '22 03:09

Ned Batchelder