django MultiValueDictKeyError error, how do I deal with it django MultiValueDictKeyError error, how do I deal with it django django

django MultiValueDictKeyError error, how do I deal with it


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


Choose what is best for you:

1

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

If is_private key is present in request.POST the is_private variable will be equal to it, if not, then it will be equal to False.

2

if 'is_private' in request.POST:    is_private = request.POST['is_private']else:    is_private = False

3

from django.utils.datastructures import MultiValueDictKeyErrortry:    is_private = request.POST['is_private']except MultiValueDictKeyError:    is_private = False


You get that because you're trying to get a key from a dictionary when it's not there. You need to test if it is in there first.

try:

is_private = 'is_private' in request.POST

or

is_private = 'is_private' in request.POST and request.POST['is_private']

depending on the values you're using.