python – django MultiValueDictKeyError error, how do I deal with it
Table of Contents
python – django MultiValueDictKeyError error, how do I deal with it
Use the MultiValueDicts 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 MultiValueDictKeyError
try:
is_private = request.POST[is_private]
except MultiValueDictKeyError:
is_private = False
python – django MultiValueDictKeyError error, how do I deal with it
You get that because youre trying to get a key from a dictionary when its 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 youre using.