简体   繁体   English

Ajax 调用不调用 Django 中的视图函数

[英]Ajax call not calling view function in Django

I am trying to build a login form in Django, and when the user hits login, I wish to send the username and password to check which type of user it is as my system has 3 different kinds of users.我正在尝试在 Django 中构建一个登录表单,当用户点击登录时,我希望发送用户名和密码来检查它是哪种类型的用户,因为我的系统有 3 种不同类型的用户。

Following is the code:以下是代码:

views.py视图.py

from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User



def index(request):
    return render(request, "login.html")


@csrf_protect
def auth_login(request):
    print("Hello !")
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    group = User.objects.get(username=username).groups.values()[0]['name']
    print(username)
    print(user)
    print(password)
    return render(request, "add_form.html")


@csrf_protect
def logout(request):
    logout(request)

login.html - (I have a simple bootstrap login form) login.html - (我有一个简单的引导登录表单)

<!DOCTYPE html>
<html lang="en">
<head>
    {% load staticfiles %}
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <title>Login</title>

<style>
        html,
body {
  height: 100%;
}

body {
  display: -ms-flexbox;
  display: -webkit-box;
  display: flex;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -webkit-box-align: center;
  align-items: center;
  -webkit-box-pack: center;
  justify-content: center;
  padding-top: 40px;
  padding-bottom: 40px;
  background-color: white;
}

.form-signin {
  width: 100%;
  max-width: 330px;
  padding: 15px;
  margin: 0 auto;
}
.form-signin .checkbox {
  font-weight: 400;
}
.form-signin .form-control {
  position: relative;
  box-sizing: border-box;
  height: auto;
  padding: 10px;
  font-size: 16px;
}
.form-signin .form-control:focus {
  z-index: 2;
}
.form-signin input[type="text"] {
  margin-bottom: -1px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}
.form-signin input[type="password"] {
  margin-bottom: 10px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}
    </style>
</head>
<body class="text-center">
   <form class="form-signin" id="login-form">{% csrf_token %}
      <img class="mb-4" src="{% static "download.png" %}" alt="Logo"  align="center" height="112" width="112">
      <h1 class="h3 mb-4 font-weight-normal">Please sign in</h1>
      <label for="inputEmail" class="sr-only">Username</label>
      <input type="text" id="uname" class="form-control" placeholder="Username" required autofocus>
      <label for="inputPassword" class="sr-only">Password</label>
      <input type="password" id="passwd" class="form-control" placeholder="Password" required>
      <div class="checkbox mb-4">
      </div>
      <button class="btn btn-lg btn-primary btn-block" id="loginbutton" type="submit">Sign in</button>

      <p class="mt-3 mb-5 text-muted">Planning Tool</p>
    </form>

<script type="text/javascript">
    $(document).ready(function () {

        $("#login-form").on('submit', function (e) {
            e.preventDefault();
            login();
        });

    function login(){
        alert($("#uname").val())
          $.ajax({
                url: {% url 'auth:Login' %},
                method : "POST",
                data : {
                    "username" : $("#uname").val(),
                    "password" : $("#passwd").val(),
                    'csrfmiddlewaretoken' :  "{{ csrf_token }}"
                },
              success : function (data) {
                  alert("successful")
              },
              failure : function (data) {
                  alert("did not pass")
              }
            });
    }

    });

</script>
</body>
</html>

urls.py网址.py

from django.conf.urls import url
from django.urls import path
from . import views
from django.conf import settings

app_name = 'auth'

urlpatterns = [
    url(r'^', views.index, name='Home'),
    path('auth-login/', views.auth_login, name='Login'),
    path('auth-logout/', views.logout, name='Logout'),
]

---- Django console ---- ---- Django 控制台 ----

(venv) C:\Users\Krushika.Tapedia\PycharmProjects\schedulingtool>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
November 26, 2019 - 11:50:45
Django version 2.2.4, using settings 'schedulingtool.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[26/Nov/2019 11:50:48] "GET / HTTP/1.1" 200 3825
[26/Nov/2019 11:50:48] "GET /static/download.png HTTP/1.1" 304 0
[26/Nov/2019 11:51:00] "POST /auth-login/ HTTP/1.1" 200 3825


I have referred different answers on the forum, I have tried with this also click here我在论坛上提到了不同的答案,我也试过这个也点击这里

but it does not enter into the function and print the first statement on the terminal.但它不会进入函数并在终端上打印第一条语句。 I am unable to debug this and not able to understand the problem here.我无法调试这个,也无法理解这里的问题。

Thanks in advance.提前致谢。

EDIT : Pasting the whole HTML File for you to try and also the Django console编辑:粘贴整个 HTML 文件供您尝试以及 Django 控制台

You probably need to change this inside the file urls.py :您可能需要在文件urls.py更改它:

url(r'^', views.index, name='Home'),

to

path(r'^', views.index, name='Home'),

From the official documentation regarding the url function来自关于url功能的官方文档

This function is an alias to django.urls.re_path() .这个函数是django.urls.re_path()的别名。 It's likely to be deprecated in a future release.它可能会在未来的版本中被弃用。

Your url function matches any string and hence all requests are sent to the index function inside your views.py file.您的url函数匹配任何字符串,因此所有请求都会发送到您的views.py文件中的index函数。

Try this: 尝试这个:

@csrf_protect
def auth_login(request):
    print("Hello !")
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            group = user.groups.values()[0]['name'] 
            print(username)
            print(user)
            print(password)

What do you mean by that: "it does not enter into the function and print the first statement ('Hello !' ? ) on the terminal." 您的意思是:“它没有进入函数并在终端上打印第一个语句('Hello!'??)。” which function ? 哪个功能?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM