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