MultiValueDictKeyError в Django 1.11.18 - PullRequest
       3

MultiValueDictKeyError в Django 1.11.18

0 голосов
/ 29 января 2019

Я использую Python 3.7 с Django 1.11.18.Я должен подключиться к базе данных Oracle 11g, и поэтому использование версии 1.11 для Django.Приведенный ниже код работал для django 2.0.7 и python 3.7, но когда я понизил версию до 1.11.18, она начала выдавать мне ошибку.

Я отправляю запрос на публикацию через форму HTML.Почтовый запрос имеет поля username и password.Код Python для получения того же: -

username = request.POST[‘username’]
password = request.POST[‘password’]

Я также пытался: -

username = request.POST.get(‘username’, False)

Приведенный выше код выбирает значение по умолчанию, даже если через мой допустимый Valuse передаетсяформа.Любая идея, почему это происходит и как ее решить.

Редактировать: - Полная часть кода ниже

views.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." );
                        });
                    });

TRACEBACK: -

[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'"
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...