我试图保存一个对象到我的数据库,但它抛出一个MultiValueDictKeyError错误。

问题在于表单,is_private是由一个复选框表示的。如果复选框未被选中,显然不会传递任何信息。这是错误被丢弃的地方。

我如何正确地处理这个异常,并捕获它?

这条线是

is_private = request.POST['is_private']

当前回答

First check if the request object have the 'is_private' key parameter. Most of the case's this MultiValueDictKeyError occurred for missing key in the dictionary-like request object. Because dictionary is an unordered key, value pair “associative memories” or “associative arrays” In another word. request.GET or request.POST is a dictionary-like object containing all request parameters. This is specific to Django. The method get() returns a value for the given key if key is in the dictionary. If key is not available then returns default value None.

你可以这样处理这个错误:

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

其他回答

为什么不尝试在模型中定义is_private为default=False?

class Foo(models.Models):
    is_private = models.BooleanField(default=False)

使用MultiValueDict的get方法。这也出现在标准字典中,是一种获取值的方法,同时在不存在时提供默认值。

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

一般来说,

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

我得到了'MultiValueDictKeyError'错误,而使用ajax与Django。只是因为在选择元素时没有输入“#”。像这样。

data:{ name : $('id_name').val(),},

然后我把'#'与id和问题解决了。

data:{ name : $('#id_name').val(),},

First check if the request object have the 'is_private' key parameter. Most of the case's this MultiValueDictKeyError occurred for missing key in the dictionary-like request object. Because dictionary is an unordered key, value pair “associative memories” or “associative arrays” In another word. request.GET or request.POST is a dictionary-like object containing all request parameters. This is specific to Django. The method get() returns a value for the given key if key is in the dictionary. If key is not available then returns default value None.

你可以这样处理这个错误:

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

选择最适合你的:

1

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

如果请求中存在is_private key。POST is_private变量将等于它,如果不是,那么它将等于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