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



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

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

<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>

当我输入正确的用户名和密码时,一切都会正常工作,我会在正确的页面上重定向,但当我输入错误的密码时,登录页面会被重新加载,没有什么告诉我密码/用户名不正确。

我知道,无论密码是正确的还是不正确的,我都会在主页上重定向,但当我没有登录时(所以当密码错误时(,这个主页会在登录页面上重定向我(因为需要登录(。

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

1(从django.contrib导入消息导入视图.py
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 %}

登录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})

最新更新