What is the difference between request.POST ['hoge'] and request.POST.get ('hoge')? I used to use request.POST ['hoge'] without thinking about anything (sorry), but I was wondering how to use it properly, so I looked it up.
The value entered in the form is returned in the dictionary.
request.POST ['hoge']
is the same as retrieving dictionary values with dictionary ['key']
.
request.POST.get ('hoge')
is the same as retrieving the dictionary value with dictionary.get ('key')
.
In the dictionary ['key']
, a KeyError
occurs when you specify a key that does not exist.
Dictionary.get ('key')
returns None
if you specify a key that does not exist.
If you set a second argument like dictionary.get ('key','default')
, the set value will be returned as the default value when the key does not exist. Therefore, the error does not occur even if the key does not exist.
If you want to raise an error, use request.POST ['hoge']
, and if you don't want to raise an error, use request.POST.get ('hoge')
.
From now on, I will use it properly ... ('▽') ゞ
Master Python dictionary types! Covers everything from basic usage to application
Recommended Posts