django ajax login,javascript - Django Ajax login form - Stack Overflow

I am trying to submit a login form using ajax. I am confused as to how I am supposed to handle the exceptions/successful responses. I am getting a 200 OK from the server and the form returns error's either by the password/username field. How can I get a error message for to display or redirect the user to the appropriate page depending on the server response?

JQUERY:

56 $(window).load(function(){

57 $('#login_form').submit(function(e){

58 e.preventDefault();

59 var request_url = document.getElementById('next').value

60 $.ajax({

61 type:"POST",

62 url: $(this).attr('action'),

63 data: $('#login_form').serialize(),

64 success: function(response){ $('#msg').text(response);

65 console.log(response);

66 },

67 error: function(xhr, ajaxOptions, thrownError){ alert( $('#login_error').text('Username already taken. Please select another one.')},

68 });

69 });

70 });

VIEW: UPDATED

51 def login(request):

52 if request.method == 'POST':

53 request.session.set_test_cookie()

54 login_form = AuthenticationForm(request, request.POST)

55 if login_form.is_valid():

56 if request.is_ajax:

57 user = django_login(request, login_form.get_user())

58 if user is not None:

59 return HttpResponseRedirect(request.REQUEST.get('next', '/'))

**else:**

61 **return HttpResponseForbidden() # catch invalid ajax and all non ajax**

60 else:

61 login_form = AuthenticationForm(request)

62

63 c = Context({

64 'next': request.REQUEST.get('next'),

65 'login_form': login_form,

66 'request':request,

67 })

68 return render_to_response('login.html', c, context_instance=RequestContext(request))

FORM:

7

8

9

10 {{ login_form }}

11

12

13

14

{{ request.get_full_path }}

15

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值