This is an old question, but in case anyone else runs into this, here is what I did. Please note:
I extended the default Django authentication system to use email address in place of the username. (My code should still work even if you use the default)
I also used the Django Rest Framework status code (but again this is optional)
You will need to set up the default Django registration templates as done here
In your views.py:
from django.shortcuts import render
from django.http import JsonResponse
from rest_framework import status
# Show the login page
def showLoginPage(request):
return render(request,'registration/login.html',{})
# Actual login logic using AJAX
def login_request(request):
if request.is_ajax and request.method == "POST":
context = {}
email = request.POST['username']
password = request.POST['password']
account = authenticate(request,username=email, password=password)
if account is None :
context['message1'] = 'Invalid Login Details!'
context['message2'] = 'Kindly Try Again With A Valid Email And Password'
context['code']=status.HTTP_401_UNAUTHORIZED
return JsonResponse(context, status = 200)
elif account is not None and not account.is_active:
context['message1'] = 'Sorry, your account is in-Active'
context['message2'] = 'Kindly Check Your Email For Activation Link Or Contact Support'
context['status'] = 'Error!'
context['code']=status.HTTP_401_UNAUTHORIZED
return JsonResponse(context, status = 200)
elif account :
login(request, account)
context['message'] = 'Successfully authenticated.'
context['status'] = 'Success!'
context['code']=status.HTTP_200_OK
return JsonResponse(context, status = 200)
else:
context['message'] = 'Invalid credentials'
context['message2'] = 'Kindly Try Again With A Valid Email And Password'
context['code']=status.HTTP_401_UNAUTHORIZED
return JsonResponse(context, status = 200)
return JsonResponse({}, status = 200)
urls.py:
# default page = login page
path('', views.showLoginPage, name='login'),
# ajax login
path('post/ajax/loginUser', views.login_request, name='loginUser'),
# home page once logged in
path('home/', views.home, name='home'),
login.html:
×
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}else{
sign_in_User()
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
const togglePassword = document.querySelector('#togglePassword');
const password = document.querySelector('#id_password');
togglePassword.addEventListener('click', function (e) {
// toggle the type attribute
const type = password.getAttribute('type') === 'password' ? 'text' : 'password';
password.setAttribute('type', type);
// toggle the eye slash icon
this.classList.toggle('fa-lock-open');
});
$("#hide_msg").click(function (){
$("#login_error_div").hide()
});
function sign_in_user() {
var url = $("#Urlhome").attr("data-url");
event.preventDefault();
event.stopPropagation();
var username = ($('#id_username')).val();
var password = ($('#id_password')).val();
$.ajax({
url: "{% url 'loginUser' %}",
type: "POST", // or "get"
headers: {'X-CSRFToken': '{{ csrf_token }}'}, // for csrf token
data:{
'username': username,
'password':password,
},
success: function loginResponse(response) {
if(response['code']=== 401){
$('#login_error_div').show();
$("#error1").text(response['message1']+' :')
$("#error2").text(response['message2'])
} else {
location.href=url;
}
}
});
}