Reputation: 371
I'm looking for a better way to code:
My Code is,
@login_required
def updateEmInfo(request):
userProfile = request.user.get_profile()
if request.POST.__contains__('userType'):
userType = request.POST['userType']
else:
userType = None
if request.method == 'POST':
~~~~~~~~
If I code as userType = request.POST['userType'],
then I get an error if userType
is not equal.
I don't think it is good idea to to use the __contains__
method, is there a better way to write this code?
Something easy like the following
userType = request.POST['userType'] ? request.POST['userType'] : None
Upvotes: 4
Views: 2703
Reputation: 55942
you can use get
request.POST.get('userType')
get(key[, default]) Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError
.
Upvotes: 4
Reputation: 2630
You can use:
userType = request.POST.get('userType', None)
This would be roughly equivalent to:
try:
userType = request.POST['userType']
except KeyError:
userType = None
Upvotes: 3