login with ajax,authentication

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;

}

}

});

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值