繁体   English   中英

如何修复 django 中的 MultiValueDictKeyError

[英]How to fix MultiValueDictKeyError in django

这是我的表格

<h1>ADD LIST</h1>
        <form action="addList/" method="post">
            {% csrf_token %}
            <div class = "container">
                <label>List Name</label><br>
                <input  name="listname" class= "listNamec"><br><br></input>
                <label>List title</label><br>
                <input name="listtitle"  class= "listTitlec"><br><br></input>  
            </div>
        </form>

这是我的 function

def addList(response):

    listname = response.POST['listname']

    list.name = listname
    list.save()

    return render(response, 'main/index.html', {})

错误:

    raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'listname'

我需要将这些添加到 Todolist 数据库,而不是工作:(

基本上,当您尝试访问MultiValueDict 中不存在的键时会发生此错误。 在获取它的值之前,您需要先验证该键是否存在:

# using the `in` keyword
if "listname" in request.POST:
    listname = response.POST["listname"]


# or using the `get` method
listname = request.POST.get("listname", False)
if listname:
    ...

确保在密钥不存在时返回错误。 此外,由于您遇到过这种情况,请验证您是否确实将表单数据正确传递到路由。 请务必阅读 django 文档并了解如何处理 forms。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM