【问题标题】:MultiValueDictKeyError at /main/add at 'num1'MultiValueDictKeyError at /main/add at 'num1'
【发布时间】:2020-03-18 17:24:02
【问题描述】:

从下面的编码项目中,我想添加两个数字并想打印它们的结果值。一切都很顺利,但是当我尝试打印结果值时,它会导致“MultiValueDictKeyError”错误。我已经搜索并尝试了很多方法,但未能解决问题。

项目树如下所示 project files tress

views.py

from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

def home(request):
return render(request, 'base.html')

@csrf_exempt
def add(request):

   val1 = int(request.POST['num1'])
   val2 = int(request.POST['num2'])
   res = val1 + val2

return render(request, "main/index.html", {'add_result': res})

Index.html

{% extends 'base.html' %}

{% block content %}

<h3>This two number adding form</h3>

<form action="{% url 'add' %}" method="POST">
    Enter the first here: <input type="text" name="num1" placeholder="First Number"><br>
    Enter the second here: <input type="text" name="num2" placeholder="Second Number"><br>
    <input type="submit">
</form>

<hr>

<div>
    Result : <p>{{ add_result }} </p>
</div>

{% endblock %}

base.html

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, 
 minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ADDTWONUMBER</title>
</head>
<body>

<H4>THIS IS FORM OF ADDING TWO NUMBER</H4>
<li><a href="main/add">click here to add two number</a></li>
<div>
{% block content %} {% endblock %}
</div>

</body>
</html>

urls.py

from django.urls import path
from . import views

urlpatterns = [
path('', views.home, name = 'home'),
path('main/add' , views.add, name = 'add'),
]

错误

> MultiValueDictKeyError at /main/add
> 'num1'
> Request Method:   GET
> Request URL:  http://127.0.0.1:8000/main/add
> Django Version:   3.0.4
> Exception Type:   MultiValueDictKeyError
> Exception Value:  'num1'
> Exception Location:   /home/hudacse6/Env/lib/python3.7/site- 
  packages/django/utils/datastructures.py in __getitem__, line 78
> Python Executable:    /home/hudacse6/Env/bin/python
> Python Version:   3.7.4
> Python Path:  
 ['/home/hudacse6/pr1_todoapps',
 '/usr/lib/python37.zip',
 '/usr/lib/python3.7',
 '/usr/lib/python3.7/lib-dynload',
 '/home/hudacse6/Env/lib/python3.7/site-packages']
> Server time:  Wed, 18 Mar 2020 17:09:20 +0000

Error in picture

如何处理这个错误?

【问题讨论】:

  • views.py 中的 return 语句没有正确缩进,它们在真实代码中吗?
  • 我只是复制并粘贴我的所有代码。如果缩进是否正确,Pycharm Pro 会自动解决。

标签: python django dictionary


【解决方案1】:

您是否尝试过在request.POST 上使用get() 方法?

val1 = int(request.POST.get('num1', None))
val2 = int(request.POST.get('num2', None))

【讨论】:

  • 让我试试这个。
  • 得到错误:int() 参数必须是字符串、类似字节的对象或数字,而不是 'NoneType'
猜你喜欢
  • 2020-05-30
  • 2018-11-13
  • 2016-08-27
  • 2021-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-13
  • 1970-01-01
相关资源
最近更新 更多