DjangoのエラーMultiValueDictKeyErrorの解決方法〜ちょびっとテクニカル

DjangoでQueryDictのエラー関係でMultiValueDictKeyErrorが出る時があります。

これをtry except文でキャッチしようとするとなかなかうまくいきません。

hugaがNULLのためにQueryDictのエラーが出る例

Exception Type: MultiValueDictKeyError at /hoge/
Exception Value: "Key 'huga' not found in "

try except文の失敗例

exceptで MultiValueDictKeyErrorを捕捉しようとしてもだめな例です。

try:
    ・
    ・
except MultiValueDictKeyError :
    pass


Djangoの公式にはこうあります。

Request and response objects

QueryDict.__getitem__(key)
Returns the value for the given key. If the key has more than one value, __getitem__() returns the last value. Raises django.utils.datastructures.MultiValueDictKeyError if the key does not exist. (This is a subclass of Python's standard KeyError, so you can stick to catching KeyError.)

MultiValueDictKeyErrorはKeyErrorのサブクラスなので、KeyErrorだったらキャッチできるよ、とあります。

聞いてないよ〜〜〜って叫びたいところですが、MultiValueDictKeyErrorをKeyErrorにすると直ります。

try:
    ・
    ・
except KeyError :
    pass

成功です。