Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a name/value pair exists when posting data?

Tags:

python

django

I'm not able to find the proper syntax for doing what I want to do. I want to do something if a name/value pair is not present. Here is the code in my view:

if (!request.POST['number']):     # do something 

What is the proper way to accomplish something like the above? I am getting a syntax error when I try this.

like image 564
djangon00b Avatar asked Jun 15 '11 17:06

djangon00b


1 Answers

@Thomas gave you the generic way, but there is a shortcut for the particular case of getting a default value when a key does not exist.

number = request.POST.get('number', 0) 

This is equivalent to:

if 'number' not in request.POST:     number = 0 else:     number = request.POST['number'] 
like image 187
Pablo Castellazzi Avatar answered Sep 23 '22 02:09

Pablo Castellazzi