django MultiValueDictKeyError error, how do I deal with it

dotty picture dotty · May 5, 2011 · Viewed 251.6k times · Source

I'm trying to save a object to my database, but it's throwing a MultiValueDictKeyError error.

The problems lies within the form, the is_private is represented by a checkbox. If the check box is NOT selected, obviously nothing is passed. This is where the error gets chucked.

How do I properly deal with this exception, and catch it?

The line is

is_private = request.POST['is_private']

Answer

adamnfish picture adamnfish · May 5, 2011

Use the MultiValueDict's get method. This is also present on standard dicts and is a way to fetch a value while providing a default if it does not exist.

is_private = request.POST.get('is_private', False)

Generally,

my_var = dict.get(<key>, <default>)