【问题标题】:How to fix MultiValueDictKeyError in django如何修复 Django 中的 MultiValueDictKeyError
【发布时间】:2022-12-12 03:10:34
【问题描述】:

这是我的表格

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

这是我的功能

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'

我需要将这些添加到待办事项列表数据库,但无法正常工作:(

【问题讨论】:

    标签: python django django-models django-views


    【解决方案1】:

    基本上,当您在MultiValueDict 中尝试access a key that does not exist 时会发生此错误。在获取它的值之前,您需要先验证该键是否存在:

    # 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 文档并了解表单的处理方式。

    【讨论】:

      猜你喜欢
      • 2019-07-15
      • 2015-03-14
      • 2017-01-14
      • 2014-06-25
      • 2020-05-24
      • 1970-01-01
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      相关资源
      最近更新 更多