[PYTHON] Differences between Django's request.POST ['hoge'] and request.POST.get ('hoge')

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

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').

Difference between dictionary ['key'] and 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.

How to use properly

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 ... ('▽') ゞ

reference

Master Python dictionary types! Covers everything from basic usage to application

Recommended Posts

Differences between Django's request.POST ['hoge'] and request.POST.get ('hoge')
Differences between Windows and Linux directories
Django's MVT-Relationship between Models and Modules-
Differences between yum commands and APT commands
Differences between symbolic links and hard links
Differences between Python, stftime and strptime
Differences between Ruby and Python in scope
Differences in syntax between Python and Java
Matplotlib Basics / Differences between fig and axes
Differences between Numpy 1D array [x] and 2D array [x, 1]
Differences in multithreading between Python and Jython
Differences between Ruby and Python (basic syntax)
Differences between queryStringParameters and multiValueQueryStringParameters in AWS Lambda
Summary of the differences between PHP and Python
Differences between glibc, musl libc and go resolvers
EP 3 Know the Differences Between bytes, str, and unicode
Differences between numpy and pandas methods for finding variance
Between parametric and nonparametric
A rough summary of the differences between Windows and Linux
I tried to enumerate the differences between java and python
Summary of Differences Between Ruby on Rails and Django ~ Basics ~