request.POST['sth'] throws a KeyError exception if 'sth' not in request.POST .
request.POST.get('sth') will return None if 'sth' not in request.POST .
In addition, .get allows you to provide an additional default parameter value, which is returned if the key is not in the dictionary. For example, request.POST.get('sth', 'mydefaultvalue')
This is the behavior of any python dictionary and does not apply to request.POST .
These two fragments are functionally identical:
The first fragment:
try: x = request.POST['sth'] except KeyError: x = None
Second snippet:
x = request.POST.get('sth')
These two fragments are functionally identical:
The first fragment:
try: x = request.POST['sth'] except KeyError: x = -1
Second snippet:
x = request.POST.get('sth', -1)
These two fragments are functionally identical:
The first fragment:
if 'sth' in request.POST: x = request.POST['sth'] else: x = -1
Second snippet:
x = request.POST.get('sth', -1)
dgel Sep 20 '12 at 18:20 2012-09-20 18:20
source share