Lotus@ 2019-05-09 23:41 采纳率: 100%
浏览 42

使用ajax登录表单django

I have a login form of Django and i want to redirect user to the landing page if the password and the username is matching and to show an alert message if the login is failed and eventually show a validation error if the form is submitted empty.

When i submit the form using the right credentials the user is logged but no message is shown on the form, on the server log i have this message 09/May/2019 23:35:52] "POST /login/ HTTP/1.1" 200 7560 when i submit an empty form i have this message Bad Request: /login/ [09/May/2019 23:36:53] "POST /login/ HTTP/1.1" 400 0 and when i submit a wrong credentials i have this message [09/May/2019 23:37:36] "POST /login/ HTTP/1.1" 200 61

This is my html form

            <div id="cd-login"> <!-- log in form -->
                  <div class="login_div"></div>
                <form id="login_form" class="cd-form" action="{% url 'login' %}" method="POST">
                {% csrf_token %}
                    <p class="fieldset">
                        <label class="image-replace cd-email" for="signin-email">E-mail</label>
                        <input class="full-width has-padding has-border" id="username" type="text" name="username" placeholder="E-mail">
                        <span class="cd-error-message">Error message here!</span>
                    </p>

                    <p class="fieldset">
                        <label class="image-replace cd-password" for="signin-password">Password</label>
                        <input class="full-width has-padding has-border" id="password" type="text" name="password"  placeholder="Password">
                        <a href="#0" class="hide-password">Hide</a>
                        <span class="cd-error-message">Error message here!</span>
                    </p>

                    <p class="fieldset">
                        <input class="full-width" type="submit" value="Login">
                    </p>
                </form>

                <p class="cd-form-bottom-message"><a href="#0">Forgot your password?</a></p>
                <!-- <a href="#0" class="cd-close-form">Close</a> -->
            </div> <!-- cd-login -->

This is my views.py

def ajax_login(request):
    if request.method == 'POST':
        username = request.POST.get('username', '').strip()
        password = request.POST.get('password', '').strip()
        if username and password:
            # Test username/password combination
            user = authenticate(username=username, password=password)
            # Found a match
            if user is not None:
                # User is active
                if user.is_active:
                    # Officially log the user in
                    return render(request, 'issueresolver/landing_page.html')

                else:
                    data = {'success': False, 'error': 'User is not active'}
            else:
                data = {'success': False, 'error': 'Wrong username and/or password'}

            return HttpResponse(json.dumps(data), content_type='application/json')

    # Request method is not POST or one of username or password is missing
    return HttpResponseBadRequest()

This my js file

$('form').on('submit', function(e) { e.preventDefault()
                $.ajax({
                  type:"POST",
                  url:  $(this).attr('action'),  
                  data: $('#login_form').serialize(),
                  beforeSend: function (xhr, settings) {
                      var csrftoken = Cookies.get('csrftoken');
                      function csrfSafeMethod(method) {
                          // these HTTP methods do not require CSRF protection
                          return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
                      }
                      if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                          xhr.setRequestHeader("X-CSRFToken", csrftoken);
                      }
                  },
                  success: function(response){

                    /* here i am supposed to redirect user if login success and show an alert error message if the login is failed */
               }
              });
            });

If any one can help me adjusting my code to be working as i described i will be more than grateful.

  • 写回答

1条回答 默认 最新

  • weixin_33743661 2019-05-10 20:43
    关注

    Finally i managed to solve the issue making some changes to the view. This is the working code :

    def ajax_login(request):
        if request.method == 'POST':
            username = request.POST.get('username', '').strip()
            password = request.POST.get('password', '').strip()
            response_data = {}
            if username and password:
                # Test username/password combination
                user = authenticate(username=username, password=password)
                # Found a match
                if user is not None:
                    login(request, user)
                    response_data['result'] = 'Success!'
                    response_data['message'] = 'You"re logged in'
                else:
                    response_data['result'] = 'Failed!'
                    response_data['message'] = 'Login Failed, Please check your credentials'
    
                return HttpResponse(json.dumps(response_data), content_type="application/json")  
    
        return render(request, 'login.html')
    
    

    ajax call

    $('form').on('submit', function(e) { e.preventDefault()
                    $.ajax({
                      type:"POST",
                      url:  $(this).attr('action'),  
                      data: $('#login_form').serialize(),
                      beforeSend: function (xhr, settings) {
                          var csrftoken = Cookies.get('csrftoken');
                          function csrfSafeMethod(method) {
                              // these HTTP methods do not require CSRF protection
                              return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
                          }
                          if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                              xhr.setRequestHeader("X-CSRFToken", csrftoken);
                          }
                      },
                      success: function(response){
                        if (response['result'] == 'Success!')
                            window.location = '/';
                        else
                            alert(response['message']);  
                   }
                  });
                });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog