Django python View and Form - MultiValueDictKeyError at /result 'num1' - 为啥我的表单不会提交数据
Posted
技术标签:
【中文标题】Django python View and Form - MultiValueDictKeyError at /result \'num1\' - 为啥我的表单不会提交数据【英文标题】:Django python View and Form - MultiValueDictKeyError at /result 'num1' - Why will my form not submit dataDjango python View and Form - MultiValueDictKeyError at /result 'num1' - 为什么我的表单不会提交数据 【发布时间】:2020-05-30 18:34:07 【问题描述】:我创建了一个表单来添加两个数字并在 /result 处接收 MultiValueDictKeyError 'num1'。我已经尝试了很多东西,但无法弄清楚。我想我会试试这个。
@project -> url.py:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from datetime import datetime
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('app1.urls')),
path('result', include('app1.urls')),
]
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
@App-> url.py:
from django.urls import path, include
from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static
from . import views
from . import urls
from app1.models import Footprint
import app1.views
urlpatterns = [
path("", views.index, name="index"),
path('result', views.calc, name='result'),
]
@App->views.py:
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpRequest,HttpResponseRedirect
from .models import Footprint
# Create your views here.
def index(request):
foots = Footprint.objects.all()
return render(request, "index.html", 'foots': foots)
def calc(request):
val1 = int(request.POST['num1'])
val2 = int(request.POST['num2'])
res = val1 + val2
return render(request,'result.html','result': res)
@templates -> index.html 文件,我在其中编写表单:
% block content %
<form action="calc" method="post">
% csrf_token %
<p style="color:white;">Installation Cost:</p> <input type="text" name="num1">
<p style="color:white;">Installation Year:</p> <input type="text" name="num2"><br><br>
<p><a href="result" class="btn btn-primary btn-lg btn-custom">SUBMIT</a></p>
</form>
% endblock %
@result.html:
% block content %
Result: result
% endblock %
@这里我出错了
MultiValueDictKeyError at /result
'num1'
Request Method: GET
Request URL: http://127.0.0.1:8000/result
Django Version: 3.0.3
Exception Type: MultiValueDictKeyError
Exception Value:
'num1'
Exception Location: C:\Users\scott\Envs\venv\lib\site-
packages\django\utils\datastructures.py in __getitem__, line 78
Python Executable: C:\Users\scott\Envs\venv\Scripts\python.exe
Python Version: 3.8.0
Python Path:
['C:\\Users\\scott\\projects\\marciano',
'C:\\Users\\scott\\Envs\\venv\\Scripts\\python38.zip',
'C:\\Users\\scott\\Envs\\venv\\DLLs',
'C:\\Users\\scott\\Envs\\venv\\lib',
'C:\\Users\\scott\\Envs\\venv\\Scripts',
'c:\\users\\scott\\appdata\\local\\programs\\python\\python38\\Lib',
'c:\\users\\scott\\appdata\\local\\programs\\python\\python38\\DLLs',
'C:\\Users\\scott\\Envs\\venv',
'C:\\Users\\scott\\Envs\\venv\\lib\\site-packages']
Server time: Fri, 14 Feb 2020 21:33:42 -0500
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/result
Django Version: 3.0.3
Python Version: 3.8.0
Installed Applications:
['app1',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):File "C:\Users\scott\Envs\venv\lib\site- packages\django\utils\datastructures.py", line 76, in __getitem__
list_ = super().__getitem__(key)
During handling of the above exception ('num1'), another exception occurred:
File "C:\Users\scott\Envs\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\scott\Envs\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\scott\Envs\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\scott\projects\marciano\app1\views.py", line 14, in calc
val1 = int(request.POST['num1'])
File "C:\Users\scott\Envs\venv\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__
raise MultiValueDictKeyError(key)
Exception Type: MultiValueDictKeyError at /result
Exception Value: 'num1'
【问题讨论】:
请分享整个错误信息。 刚刚将其添加到帖子的末尾。 【参考方案1】:在您的代码模板 -> index.html 文件中,您在其中编写表单指定操作更改 calc
到 result
并删除 a
和 href
并添加 <button type='submit'>submit</button>
@index.html
% block content %
<form action="result" method="post"> #here change the action
% csrf_token %
<p style="color:white;">Installation Cost:</p> <input type="text" name="num1">
<p style="color:white;">Installation Year:</p> <input type="text" name="num2"><br><br>
<p><button type='submit' class="btn btn-primary btn-lg btn-custom">SUBMIT</button></p>
# here above you change the remove a and href='result' it reference and add submit button for submit the data
</form>
% endblock %
@apps -> url.py
path('result', views.calc, name='result'), #here you name your url is result
因为您命名您的 url 结果也是删除硬代码的最佳实践删除 url 使用该 % url % 模板标签
并在您的视图中使用 get 函数,您可以在其中获得 num1
和 num2
@views->views.py
def calc(request):
val1 = int(request.POST.get('num1 ',1)) # here use the get method of dictionary see in python docs
val2 = int(request.POST.get('num2',1)) # also same change use get method num2 is key and 1 is default value
res = val1 + val2
return render(request,'result.html','result': res)
get()
method 给出一个 key 的值 如果方法没有找到任何 key 它会返回默认值 如果我们没有传递默认值则传递 1None
在这里你对你的代码进行更改,如果它有效,请为这个问题做出正确的答案,最终让我知道这项工作与否
【讨论】:
首先,感谢 cmets。二是这类作品。现在它只是将 num1 和 num2 的两个默认值相加。所以结果总是 2。另外,我尝试使用模板标签,当我提交表单时,它只是让我回到主页。我可能使用不正确。再次感谢您的帮助! 首先,感谢 cmets。二是这类作品。现在它只是将 num1 和 num2 的两个默认值相加。所以结果总是 2。另外,我尝试使用模板标签,当我提交表单时,它只是让我回到主页。我可能使用不正确。再次感谢您的帮助! @feather 我更新我的答案让检查它是否工作你也忘记了表单中的添加提交按钮不是'锚标签'a和href ='result'删除它按照获取请求而你没有提交它重定向你的数据,如果它工作或不让我知道 你是个巫师!那解决了它。非常感谢! 你能接受你的问题的答案是正确的吗以上是关于Django python View and Form - MultiValueDictKeyError at /result 'num1' - 为啥我的表单不会提交数据的主要内容,如果未能解决你的问题,请参考以下文章
python3开发进阶-Django视图(View)的常见用法
python view_graph_nodes_and_edges
Python自动化运维:Django之View视图和Template