How to Fix MultiValueDictKeyError in Django

The MultiValueDictKeyError in Django occurs when attempting to access a dictionary key that doesn't exist. To fix the error you need to provide a default value if there is no key in the specified dict. In this tutorial we will go through two ways to solve this problem.

 

Django .get() Method MultiValueDictKeyError Fix

The Django second argument of the Django .get() method is the default value to use if the key doesn't exist. Here is the syntax:

 

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

 

Here is a typical example of getting a key value from a POST request. If the key "status" doesn't exist, foo is set to False.

 

foo = request.POST.get('status', False)

 

Django MultiValueDictKeyError if in Data

Another approach is to check if the key is in the dict else use a different value. In the example below if the key "split" isn't in the dict data, use the initial value from form['split'] instead.

 

split = data['split'] if 'split' in data else form['split'].initial