django MultiValueDictKeyError error, how do I deal with it

350,736

Solution 1

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

Solution 2

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

Solution 3

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.

Solution 4

Another thing to remember is that request.POST['keyword'] refers to the element identified by the specified html name attribute keyword.

So, if your form is:

<form action="/login/" method="POST">
  <input type="text" name="keyword" placeholder="Search query">
  <input type="number" name="results" placeholder="Number of results">
</form>

then, request.POST['keyword'] and request.POST['results'] will contain the value of the input elements keyword and results, respectively.

Solution 5

Why didn't you try to define is_private in your models as default=False?

class Foo(models.Models):
    is_private = models.BooleanField(default=False)
Share:
350,736

Related videos on Youtube

dotty
Author by

dotty

Hmm not alot really.

Updated on August 11, 2021

Comments

  • dotty
    dotty almost 3 years

    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']
    
    • rzetterberg
      rzetterberg about 13 years
      A good idea would be to show us the whole error and the trace. Also show us more of that portion of code where the error is raised.
    • Amrit
      Amrit over 7 years
      Can anyone explain why does this error occurs?I have seen this error when i use different Modelviewset in django rest.....
    • ThePhi
      ThePhi almost 7 years
      it means simply: the key 'is_private' doesn't exist!
  • Joe
    Joe about 13 years
    Really can't recommend number 3.
  • Joe
    Joe about 13 years
    It just seems like an abuse of the exception system. Exceptions should be for handling exceptional behaviour (i.e. behaviour you know that may happen, and must deal with, but that you don't expect in the normal program flow). In this case, the exception will be thrown and caught in 50% of the possible program flows. Added to that is the slow-down. I don't know the details of how it works in Python, but I would imagine an expensive stack-trace would be involved.
  • Akseli Palén
    Akseli Palén over 11 years
    from django.utils.datastructures import MultiValueDictKeyError
  • bjudson
    bjudson over 10 years
    @Joe - In Python this approach is pretty common. If you're catching the exception it won't automatically generate a stacktrace. docs.python.org/2/glossary.html#term-eafp
  • Joe
    Joe over 10 years
    @bjudson I know, exceptions are used for all kinds of things, not all of them necessarily how the language designers intended. Case in point the outrage caused by java.io.EOFException, plenty of disagreement on that. I wouldn't recommend using a try/catch for non-exceptional control flow, even if it works, as it's not how checked exception were designed. I accept that it's an opinion rather than fact.
  • Joe
    Joe over 10 years
    And I'm not sure that this is a valid application of EAFP anyway. If you always expected to see an is_private argument to your Django view, then requesting it and dealing with the exception would be the right way to do it. If, however, it's an optional argument that may or may not be present, then your code should reflect that.
  • Apollo Data
    Apollo Data over 7 years
    That wouldn't prevent the error he is getting checking the POST by hand for the value.
  • Bobort
    Bobort over 6 years
    There is nothing wrong with step 3. We call that Easier to ask for forgiveness than permission (EAFP), and it is a highly recommended coding style in Python. Plenty of posts on StackOverflow have even discussed this.
  • Jesus Almaral - Hackaprende
    Jesus Almaral - Hackaprende over 6 years
    This gives me a None value but I am sending the value on the POST :/
  • WesternGun
    WesternGun about 6 years
    It is the correct behaviour.. checkbox send checked when is checked but will send null if not checked. You can check this in the Chrome/Firefox DEV tool's "Network" panel. That is why you set False as the default value: if got null, make it false.