Shinichi-MJ
Shinichi-MJ

Reputation: 39

DJango doesn't execute request.method == "post" with ajax data submission

It's my first time working with JQuery and Ajax, I've been stuck on this problem for past few hours, searched through various similar solutions but nothing worked for me

Problem

Whenever I click on "submit" button Ajax delivers data to DJango view but that if "post" request part refuses to execute but else part executes no matter how many times i change the code

HTML

<form id="login-form" class="LoginForm" action="" method="post">
    {% csrf_token %}
    <h3 class="text-center text-info">Login</h3>
    <div class="error">

    </div>
    <div class="box">
        <div class="form-group">
            <label for="username" class="text-info">Username:</label><br>
            <input type="text" name="username" id="username" class="form-control">
        </div>
        <div class="form-group">
            <label for="password" class="text-info">Password:</label><br>
            <input type="text" name="password" id="password" class="form-control">
        </div>
        <div class="form-group">
            <label for="remember-me" class="text-info"><span>Remember me</span> <span><input
                        id="remember-me" name="remember-me" type="checkbox"></span></label><br>
            <input type="submit" name="LoginButton" id="LoginButton" class="btn btn-info btn-md"
                value="submit">
        </div>
    </div>
    <div id="register-link" class="text-right">
        <a href="#" class="text-info">Register here</a>
    </div>
</form>

script

$(document).ready(function () {
  $("#LoginButton").click(function () {
    var username = $("#username").val();
    var password = $("#password").val();
    if ($.trim(username).length > 0 && $.trim(password).length > 0) {
      alert("Username and password were trimmed");
      console.log("Username = " + username + "\n Password = " + password);
      $.ajax({
        url: '{% url "loginCheck" %}',
        method: "post",
        data: {
          username: username,
          password: password,
          csrfmiddlewaretoken: "{{ csrf_token }}",
        },
        cache: false,
        beforeSend: function () {
          $("#LoginButton").val("Checking...");
        },
        success: function (data) {
          console.log(data);
          var dataSet = JSON.parse(data);
          alert("Username is: " + username + " Password is: " + password);
          console.log(data.status);
          if (data.status == "ok") {
            window.location.href = "check.html";
          } else if (data.status == 0) {
            alert("Can't resolve the username and password");
            console.log(data);
          } else {
            $("#error").html('<span class="text-danger">Invalid username or password</span> ');
            $("#login-form").effect("Shake", options, 800);
          }
        },
      });
    } else {
      alert("Please enter data, Null not allowed");
    }
  });
});

view.py

def loginCheck(request):
    if request.is_ajax():
        print("AJAX sent data!!!!")
    else:
        print("DJANGO brought data!!!")

    if request.method == "post":
        print("!!!!!!!~~~~~~~~~~~~~~Executed~~~~~~~~~~~~~~!!!!!!!!")
        username = request.post.get("username")
        password = request.post.get("password")
        rePack = request.session["username"] = username
        print("Values: \n Username = " + username + " \n with session = " + rePack)

        # Validate values with database here

        return JsonResponse({"status": "ok"})
    else:
        print("\n !!!~~~~Else block was executed~~~!!! \n")
        return JsonResponse({"status": 0})

Traceback

    [27/May/2021 18:38:40] "POST /loginCheck HTTP/1.1" 500 59
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 51188)
Traceback (most recent call last):
  File "Python36-32\lib\wsgiref\handlers.py", line 138, in run
    self.finish_response()
  File "Python36-32\lib\wsgiref\handlers.py", line 180, in finish_response
    self.write(data)
  File "Python36-32\lib\wsgiref\handlers.py", line 274, in write
    self.send_headers()
  File "Python36-32\lib\wsgiref\handlers.py", line 332, in send_headers
    self.send_preamble()
  File "Python36-32\lib\wsgiref\handlers.py", line 255, in send_preamble
    ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1')
  File "Python36-32\lib\wsgiref\handlers.py", line 453, in _write
    result = self.stdout.write(data)
  File "Python36-32\lib\socketserver.py", line 775, in write
    self._sock.sendall(b)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "Python36-32\lib\wsgiref\handlers.py", line 141, in run
    self.handle_error()
  File "Python36-32\lib\site-packages\django\core\servers\basehttp.py", line 119, in handle_error
    super().handle_error()
  File "Python36-32\lib\wsgiref\handlers.py", line 368, in handle_error
    self.finish_response()
  File "Python36-32\lib\wsgiref\handlers.py", line 180, in finish_response
    self.write(data)
  File "Python36-32\lib\wsgiref\handlers.py", line 274, in write
    self.send_headers()
  File "Python36-32\lib\wsgiref\handlers.py", line 331, in send_headers
    if not self.origin_server or self.client_is_modern():
  File "Python36-32\lib\wsgiref\handlers.py", line 344, in client_is_modern
    return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
TypeError: 'NoneType' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "Python36-32\lib\socketserver.py", line 639, in process_request_thread
    self.finish_request(request, client_address)
  File "Python36-32\lib\socketserver.py", line 361, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "Python36-32\lib\socketserver.py", line 696, in __init__
    self.handle()
  File "Python36-32\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle
    self.handle_one_request()
  File "Python36-32\lib\site-packages\django\core\servers\basehttp.py", line 197, in handle_one_request
    handler.run(self.server.get_app())
  File "Python36-32\lib\wsgiref\handlers.py", line 144, in run
    self.close()
  File "Python36-32\lib\site-packages\django\core\servers\basehttp.py", line 114, in close
    super().close()
  File "Python36-32\lib\wsgiref\simple_server.py", line 35, in close
    self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'

A couple of things i tried out in order to solve the problem:

  1. I tried changing ajax "method" to "type" but that returns "NonType" object "split" error
  2. I tried changing browser to Brave from Firefox because Firefox kept terminating the connection on host machine (that's what the error said) but it's working just fine on brave
  3. I tried printing username and password on console (brave), but oddly enough it shows username and password but it blinks and disappears
  4. I tried removing "post" method validator but it returned "NonType" error in terminal
  5. Changed method to "get" instead of "post" i can see url on VSC terminal but that's about it

Edit : python version = 3.6.5 django version = 3.1.2

Edit 2: added Traceback

Upvotes: 0

Views: 350

Answers (1)

AKX
AKX

Reputation: 169338

Django

request.method is always upper-case.

You'll need

if request.method == "POST":

in your view.

(In the future, you could do a bit of print debugging: a print(request.method) in your view and look at the Django console would have solved this for you.)

Frontend

Since you're doing your POSTing with AJAX on a submit button, you will need to prevent the default submit action too. Otherwise your browser will also navigate to another page.

Turn

$("#LoginButton").click(function () {

into

$("#LoginButton").click(function (event) {
  event.preventDefault();

to prevent the default action.

Upvotes: 3

Related Questions