MultiValueDictKeyError位于/ main / add,位于'num1'

时间:2020-03-18 17:24:02

标签: python django dictionary

从下面的编码项目中,我想添加两个数字并希望打印其结果值。一切都进行得很顺利,但是当我尝试打印结果值时,它使我引起“ 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

如何处理此错误?

1 个答案:

答案 0 :(得分:1)

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

val1 = int(request.POST.get('num1', None))
val2 = int(request.POST.get('num2', None))
相关问题