MultiValueDictKeyError at /main/add at 'num1'



在下面的编码项目中,我想添加两个数字,并打印它们的结果值。一切都很顺利,但当我试图打印结果值时,它会导致"MultiValueDictKeyError"错误。我找了很多方法,但都没能解决问题。

项目树如下项目文件树

视图.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

图片错误

如何处理这个错误?

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

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

相关内容

最新更新