Django Ajax login form

后端 未结 2 1651
终归单人心
终归单人心 2021-02-06 05:57

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

2条回答
  •  终归单人心
    2021-02-06 06:43

    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.

提交回复
热议问题