我在执行代码时收到下面提到的错误:-
MultiValueDictKeyError at /count/'text box'Request Method: GET Request URL:http://127.0.0.1:8000/count/Django版本: 2.1异常类型: MultiValueDictKeyError异常值:'text box'异常位置: /Users/rajans/anaconda3/lib/python3.7/site-packages/django/utils/datastructures.py在getitem79行Python可执行文件: /Users/rajans/anaconda3/bin/pythonPython版本: 3.7.0 Python路径:['/用户/rajans/文档/djangoproject/wordcount','/用户/rajans/anaconda3/lib/python37.zip','/用户/rajans/anaconda3/lib/python3.7/lib-dynload','/用户/rajans/anaconda3/lib/python3.7/lib-dynload','/用户/rajans/anaconda3/lib/python3.7/site-pack']服务器时间: 2月5日星期二
蟒
from django.http import HttpResponse
from django.shortcuts import render
def homepage(request):
return render(request,'home.html')
def contact(request):
return HttpResponse("<h2> This is a contact_us page</h2><br> You can write to rajan.sharma@freshworks.com for any query")
def count(request):
data=request.GET['textbox']
data_list=split(data)
data_len=len(data_list)
return render(request,'count.html',{'length':data_len})
--------
<h1>Word Count</h1><br>
This is the home page for the Word count.
<form action="{% url 'count' name%}"> <!-- "{% url 'count' %}". this will load the url even if the path is changed..it will look for the name count-->
<textarea name="textbox" cols=40 rows="10"></textarea><br/>
<input type="submit" value="count"/>
</form>
count.html
<h1>Counted</h1><br/>
The length is :- {{length}}
看起来你没有在URL中将教科书变量作为参数传递。
尝试将您的URL称为/count_url/?textbook= "你想传递的价值观"
此外,建议使用.get方法作为
data = request.GET.get('textbook', None)
if data:
# do something
您正在使用http://127.0.0.1:8000/count/这个url,当这个url调用函数时,它将使用函数中的GET方法,您正在尝试访问一个“文本框”,但在第一次访问时,文本框参数不存在,所以它显示错误
您需要修改视图函数并编写一个条件
def count(request):
data=request.GET.get('textbox', None)
if data:
data_list=split(data)
data_len=len(data_list)
return render(request,'count.html',{'length':data_len})
else:
return render(request,'add here your html page name where input form is there')
使用多值词典的 get 方法,如果文本框
不存在,您还可以提供默认值。
data=request.GET.get('textbox', None)
if data:
#process
else:
#process