python - django 1.11.18 中的 MultiValueDictKeyError
问题描述
我将 Python 3.7 与 Django 1.11.18 一起使用。我必须连接到 Oracle 11g 数据库,这就是为什么使用 django 的 1.11 版本。下面的代码适用于 django 2.0.7 和 python 3.7,但是当我将我的版本降级到 1.11.18 时,它开始给我错误。
我正在通过 HTML 表单发送发布请求。发布请求具有字段用户名和密码。检索相同的python代码是:-
username = request.POST[‘username’]
password = request.POST[‘password’]
我也试过: -
username = request.POST.get(‘username’, False)
即使通过我的表单传递了有效的值,上面的代码也会选择默认值。知道为什么会发生这种情况以及如何解决它。
编辑:-代码的完整部分如下
视图.py
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request)
request.session['userName'] = username
return HttpResponse("SUCCESS")
else:
return HttpResponse("FAILURE")
HTML
$( "#loginForm" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
var jqxhr = $.post( "http://127.0.0.1:8000/ScApp2/xxxx/", $( "#loginForm" ).serialize(), function() {
})
.done(function( data ) {
if( data == "SUCCESS")
window.location.href = 'http://127.0.0.1:8000/ScApp2/home/xxxx.html';
else
alert("Please check your username and password and try again.");
})
.fail(function() {
alert( "ERROR : Please contact the Support Team." );
});
});
追溯:-
[28/Jan/2019 17:12:24] "POST /xxxx/xxxx/ HTTP/1.1" 200 7
Internal Server Error: /xxxx/xxxx/ScorecardApp20/
Traceback (most recent call last):
File "c:\users\xxxx\xxxx\local\programs\python\python37\lib\site-packages\django\utils\datastructures.py", line 83, in __getitem__
list_ = super(MultiValueDict, self).__getitem__(key)
KeyError: 'username'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\users\xxxx\xxxx\local\programs\python\python37\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
response = get_response(request)
File "c:\users\xxxx\xxxx\local\programs\python\python37\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "c:\users\xxxx\xxxx\local\programs\python\python37\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\PythonWorkspace\xxxx\xxxx\views.py", line 67, in home
username = request.POST['username']
File "c:\users\xxxx\xxxx\local\programs\python\python37\lib\site-packages\django\utils\datastructures.py", line 85, in __getitem__
raise MultiValueDictKeyError(repr(key))
django.utils.datastructures.MultiValueDictKeyError: "'username'"
解决方案
推荐阅读
- python - 在具有索引Python数的Excel工作表中搜索特定字符串
- if-statement - x86汇编中条件语句的实现
- ruby-on-rails - 通过一系列控制器传递 Rails 请求?
- python - 将scrapy数据打印到csv
- r - 无法绘制逻辑回归图
- java - 启动应用程序时显示异常 - org.openqa.selenium.WebDriverException:
- php - 如何在 php 中调整 Jquery jtable 列宽?
- mysql - MySQL:连接三个表
- shell - 需要使用 Shell 根据 csv 中的特定列检查和更新行
- java - Java:接收三个数字(short、int、long),方法必须返回最大的数字