有没有一种简单的方法可以知道 Django 登录是否失败?

时间:2021-04-28 10:11:08

标签: python html django authentication

我目前正在使用 Django 内置登录功能。正如你在这张图片上看到的那样,我只制作了我自己的表格: Login page

这真的很基础。只有两个输入和一些格式:

<form action="#" class="login-form" method="post">
    <input type="text" class="form-control input-field" placeholder="Username" name="username" required>
    <input type="password" class="form-control input-field" name="password" placeholder="Password" required>
</form>

当我输入正确的用户名和密码时,一切正常,我被重定向到正确的页面,但是当我输入错误的密码时,登录页面只是重新加载,没有任何信息告诉我密码/用户名不正确。< /p>

我明白,无论密码正确或错误,我都被重定向到主页,但是当我没有登录时(所以当密码错误时),这个主页将我重定向到登录页面(因为它需要登录)。

你知道有没有一种简单的方法可以检测登录是否失败并显示出来?

2 个答案:

答案 0 :(得分:0)

1)导入view.py
从 django.contrib 导入消息
2)在登录视图中--

 try:
    User.object.get(email=request.Post['email'])
except :
    messages.Error("User Not Found")

3)Html 文件

{% if messages %}

  {% for message in messages %}
    <div class="alert alert-{% ifequal message.tags 'error' %}danger {% else %}{{ message.tags }} {% endifequal%} alert-dismissible fade show" role="alert">
        {{ message }}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </button>
    </div>
    {% endfor %} 
{% endif %}

答案 1 :(得分:0)

在登录html

$("#login_form").on("submit", function (e) {
  e.preventDefault();
  data = {
    "email": $("#id_email").val(),
    "password": $("#id_password").val(),
  };
  if (data){
      $.ajax({
        type: "POST",
        url: `${URL}/user/login/`,
        data: data,
        success: function (data) {
           Swal.fire({
              title:  data.success,
              icon: 'success',
              confirmButtonColor: '#3085d6',
            }).then((result) => {
               window.location =`${URL}`
            })
        },
        error: function (err) {
          Swal.fire({
              title:  err["responseJSON"]["error"],
              icon: 'error',
              confirmButtonColor: '#3085d6',
            }).then((result) => {
            })
        },
      });
  }

});

在登录视图中

 if request.method == 'POST':
    try:
        user = User.objects.get(email=request.POST['email'])
        user = authenticate(request, username=request.POST['email'],
                                password=request.POST['password'])
        if user is not None:
            auth_login(request, user)   
            return JsonResponse({"success": 'Successfully User Login.'}, status=200)
    except:
        return JsonResponse({"error": str(request.POST['email'])+' is not registered with us'}, status=400)
return render(request, 'allauth/account/login.html', {"URL": settings.URL})
相关问题