Django的Ajax的登录表单 [英] Django Ajax login form

查看:383
本文介绍了Django的Ajax的登录表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提交使用AJAX登录表单。我很困惑,怎么我应该处理异常/成功响应。我从服务器得到一个200 OK的形式返回错误的或者通过密码/用户名字段。我怎样才能获得显示或将用户重定向到依赖于服务器的响应?

相应的页面错误信息

JQUERY:

  56 $(窗口).load(函数(){
57 $('#login_form)。递交(函数(五){
58ËpreventDefault();
59 VAR request_url =的document.getElementById(下一步)。值
60 $。阿贾克斯({
61型:POST,
62网址:$(本).attr(行动),
63数据:$('#login_form')序列化()。
64成功:函数(响应){$('#味精)文本(响应);
65的console.log(响应);
66},
67错误:函数(XHR,ajaxOptions,thrownError){警报($('#login_error)文本('。用户名已经采取请选择另一个')},
68});
69});
70});
 

查看:更新时间:

  51 DEF登录(要求):
52,如果request.method =='POST':
53 request.session.set_test_cookie()
54 login_form = AuthenticationForm(请求,request.POST)
55,如果login_form.is_valid():
56,如果request.is_ajax:
57用户= django_login(请求,login_form.get_user())
58,如果用户不是无:
59回的Htt presponseRedirect(request.REQUEST.get('下一个','/'))
           **其他:**
61 **返回的Htt presponseForbidden()#捕捞无效Ajax和所有非AJAX **
60其他:
61 login_form = AuthenticationForm(要求)
62
63 C =上下文({
64'下一个':request.REQUEST.get(下一步),
65'login_form:login_form,
66请求:要求,
67})
68返回render_to_response('的login.html',C,context_instance = RequestContext的(要求))
 

FORM:

  7< TT ID =login_error>< / TT>
8示形式ID =login_form行动=的方法=邮报>
9
10 {{login_form}}
11<输入类型=提交值=登陆/>
12<输入类型=隐藏ID =request_pathNAME =下一个值=//>
13 LT; /形式GT;
14其中p为H.; {{request.get_full_path}}&所述; / P>
15℃; TT ID ='味精'>< / TT>
 

解决方案

虽然它肯定是更好的做法,用JSON做到这一点,你可以逃脱不,假设你没有真正传递很多信息从服务器传回。在Django的侧换出的的Htt presponseRedirect 的Htt presponse 使用重定向URL作为你的信息。还添加了一个的Htt presponseForbidden 的情况下AJAX登录失败。

 高清登录(要求):
    如果request.method =='POST':
        request.session.set_test_cookie()
        login_form = AuthenticationForm(请求,request.POST)
        如果login_form.is_valid():
            如果request.is_ajax:
                用户= django_login(请求,login_form.get_user())
                如果用户不是无:
                    返回的Htt presponse(request.REQUEST.get('下一个','/'))
        返回的Htt presponseForbidden()#捕捞无效Ajax和所有非AJAX
    其他:
        login_form = AuthenticationForm()
    C =上下文({
        下一步:request.REQUEST.get(下一步),
        login_form:login_form,
        请求:要求,
    })
    返回render_to_response('的login.html',C,context_instance = RequestContext的(要求))
 

然后在JavaScript端,检查响应的状态code。如果是200,那么这就是你的的Htt presponse - 要重定向到URL中的响应消息。如果是403,那么这就是你的Htt presponseForbidden - 登录失败。你可以逃脱一个标准的登录失败的错误消息。

  $。阿贾克斯({
    键入:POST,
    网址:$(本).attr(行动),
    数据:$('#login_form')序列化()。
    //成功函数被调用的HTTP 200响应的情况下
    成功:函数(响应){
        //重定向到所需的网址
        了window.location =响应;
     },
    错误:函数(XHR,ajaxOptions,thrownError){
        警报('登录失败 - 请重试);
    },
});
 

我怕我没有测试过这一点,但它应该给你一个想法。

有关更多信息看文档的Django的Htt的presponse对象。然后检查出的jQuery AJAX文档

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   <tt id="login_error"></tt>                                                                                                                            
8   <form id="login_form" action="" method="post">                                                                                            
9                                                                                                                                             
10     {{ login_form }}                                                                                                                        
11     <input type="submit" value="login"/>                                                                                                    
12     <input type="hidden" id="request_path" name="next" value="/"/>                                                                          
13   </form>                                                                                                                                   
14 <p>{{ request.get_full_path }}</p>                                                                                                          
15 <tt id='msg'></tt>         

解决方案

Although it's certainly better practice to do this with a json, you can get away without, assuming you're not really passing much info back from the server. On the django side swap out the HttpResponseRedirect for an HttpResponse using the redirect URL as your message. Also add an HttpResponseForbidden for the case that ajax login fails.

def login(request):                                                                                                                         
    if request.method == 'POST':                                                                                                            
        request.session.set_test_cookie()                                                                                                   
        login_form = AuthenticationForm(request, request.POST)                                                                              
        if login_form.is_valid():                                                                                                           
            if request.is_ajax:                                                                                                             
                user = django_login(request, login_form.get_user())                                                                         
                if user is not None:                                                                                                        
                    return HttpResponse(request.REQUEST.get('next', '/'))   
        return HttpResponseForbidden() # catch invalid ajax and all non ajax                                                        
    else:                                                                                                                                   
        login_form = AuthenticationForm()                                                                                                                                        
    c = Context({                                                                                                                           
        'next': request.REQUEST.get('next'),                                                                                                
        'login_form': login_form,                                                                                                                         
        'request':request,                                                                                                                  
    })                                                                                                                                      
    return render_to_response('login.html', c, context_instance=RequestContext(request))

Then on the javascript side, check the status code of the response. If it's 200, then that's your HttpResponse - you want to redirect to the url in the response message. If it's a 403, then that's your HttpResponseForbidden - login has failed. You can get away with a standard 'login failed' error message.

$.ajax({                                                                                                                           
    type:"POST",                                                                                                                    
    url: $(this).attr('action'),                                                                                                    
    data: $('#login_form').serialize(),  
    // the success function is called in the case of an http 200 response                                                                                  
    success: function(response){ 
        // redirect to the required url
        window.location = response;                                                                                                     
     },                                                                                                                              
    error: function(xhr, ajaxOptions, thrownError){
        alert('login failed - please try again'); 
    }, 
}); 

I'm afraid I haven't tested this, but it should give you an idea.

For more info look at the docs for django's HttpResponse objects. Then check out the jquery ajax docs.

这篇关于Django的Ajax的登录表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆