django MultiValueDictKeyError 错误,我该如何处理 [英] django MultiValueDictKeyError error, how do I deal with it

查看:34
本文介绍了django MultiValueDictKeyError 错误,我该如何处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个对象保存到我的数据库中,但它抛出了一个 MultiValueDictKeyError 错误.

I'm trying to save a object to my database, but it's throwing a MultiValueDictKeyError error.

问题出在表单中,is_private 由复选框表示.如果未选中该复选框,则显然没有通过.这是错误被解决的地方.

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?

线是

is_private = request.POST['is_private']

推荐答案

使用 MultiValueDict 的 get 方法.这也存在于标准字典中,是一种获取值的方法,同时提供默认值(如果不存在).

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)

一般来说,

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

这篇关于django MultiValueDictKeyError 错误,我该如何处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆